Making images interactive and swappable using php, mysql and jquery - php

Grateful for any help on this. I'm very new to all this stuff.
I've created a jquery 'live search' form that links the input characters of a form to associated images of letter artwork in my mysql database (e.g., user enters f-l-o-w-e-r in live search and php echos six images).
Here's the php code for reference, which passes the images to a div in index.php:
foreach(str_split($_POST['search_term']) as $alpha)
{
echo "<img src='../delete/images/{$alpharray[$alpha][0]['imagePath']}' width='100' height='140'></src></a>";
}
I'd like a user to click on one of these images to open a carousel of related images from which s/he could drag and drop a new image to swap out the old one. Eventually they could submit the entire self-selected array of letters as an order.
From the jquery side, I can figure out the carousel and how to make something draggable, droppable. But I'm having trouble mentally mapping how I do the swappable part. Make a new array? Maybe someone can help set me straight with some hints...?
Thanks so much!

Not sure what exactly your problem is, but you could read the sources of the images which an .each() and post them to your php script. As it seems there you have an array which holds all the data, and you just read the elements you want. So you could just overwrite the elements that you want to change, or create a new array, depending on what exactly you want to do. And also you tagged your question mysql, not quite sure how your data is stored.
Edit:
Alright, I see two possible ways here. One would be creating all the images to each image in a div right on creation like this:
foreach(str_split($_POST['search_term']) as $alpha)
{
echo "<img class="clickable" src='../delete/images/{$alpharray[$alpha][0]['imagePath']}' width='100' height='140'></src></a>";
echo '<div class="editimages">';
// Code that creates the images with which the above image can be replaced
echo '</div>';
}
Downside is, that the user gets all the images at the same time which might be loading slow and creating alot of traffic. Upside is, that it the easiest solution, and will react fast when the user clicks. You could just do something like
$(".clickable").click(function(){
$(".editimages").hide();
$(this).next().show();
});
In your JS.
The other solution would be loading the images on click, at the moment the user wants to edit one. Upside is, that it will only load the images you need and so save traffic and load faster on init, but it will start to get the replacement images when the user wants to see them, so depending on how fast the server is and how big the images are, this might feel a bit slower.

Related

There's got to be a better way to store and retrieve images from a database, Right?

I've been following multiple tutorials on uploading and retrieving images using MySQL and PHP, and they all seem to be using the same technique; upload the image as normal (no problem there) and then create another document and use a PHP script to select the image from the database then change the 'content-type' to image/jpeg, then display said document in an iframe.
That's fine and dandy; if I wanted to display one single image, and I was fine with it being in an iframe. However, I'm developing a CMS(like) system where the end user will be changing many styled images on a particular page and that technique doesn't quite work, as it appears to only work for single image.
I'm not looking to upload the files to a folder, then store the path in the database either. I'd like to store the image itself in the database.
I know this is a broad question and I definitely don't expect anyone to give me a step by step tutorial. But if you could direct me to one that would be great.
Thanks in advance.
The page used to display the image in the way you outline the tutorials show, with retrieval and then a header output is a way that sets the PHP image-calling file to act as an image file .
So you can have
<img src='phpimagefile.php?id=imgreference' alt'my image'>
for example.
If you want to display multiple images like this then you can simply roll the above HTML code into a foreach or similar loop on another page.
foreach ($imagesSet as $image){
print "<img src='phpimagefile.php?id=".$image['id']."' alt'my image'>\n";
}
Edit:
You can get really smart and with some mod_rewrite you can actually store images with filepath names such as :
<img src='/images/45757/goldenShower.jpg' alt='My Image'>
And the mod_rewrite will reorganise this to be able to find the image of:
<img src='/images/phpimagefile.php?id=45757' alt'my image'>
.
Storing the images directly in the database is cumbersome and does not solve your (apparent) problem of retrieval.
If you can clarify why being in the database is better for the image than a image output file as I describe above, this will probably show more people (judging from the comments) exactly what your current issue is.
Some Notes:
Don't use iframes. Use the HTML img tag as I example above.
We can't direct you to any tutorial until we actually understand what you're trying to gain.
Even if you upload the files to a database table, you are still going to need to store a reference to that table/row in order to reference the correct image, so imageId = 'files/image/goldenShower.jpg' is just another reference in the Database like imageId = 4365 would be.

jquery map dynamically create cells

I'm working on a basic map that is organized in the standard X/Y coordinate fashion. At each coordinate (x,y), there are contents that are stored in the database (the contents for each location is loaded via php/mysql database).
At my current setup, the map is just placed in the page as a static object, and I've used jquery/ajax to update the display and data for the coordinates.
I'm looking for a way to have a dynamically loaded click & Drag map, that will load cells as they are needed. (what ever comes into your view--in this case the window, should be loaded from the server--a div be created with the proper coordinates relative to its surrounding cells).
As of right now, my static map has this setup:
http://i.stack.imgur.com/LeVYO.gif (link because i cannot post pics)
The images are placed row by row (z index changing as each row goes down to give the appearance of overlap).
If that same pattern were to be duplicated, to dynamically create those cells, you can see that when a row sticks out on the right side, there is room on the left side, leaving easy overlapping.
I haven't been able to find any way to accomplish this:
1) When a cell (region with multiple coordinates inside) is visible, check to see if the surrounding 8 cells are already loaded.
2) If a surrounding 1 of 8 cells are not loaded, create the cell in the correct position, and assign the 'center coord' so that the generated data has a reference point.
3) Ensure that the cells are movable via click&drag, as well as the ability to click on the objects under (to interact).
4) Cells cannot be accessed by scrolling (scroll bar)
I have a feeling its fairly complicated, but I'm looking for the best way to do it, so ANY help or direction would be great!
With all my desire to help, I really cannot give the answer that will solve the problem, which I apologize for, but I think I can try to direct you to something.
It's the HTML 5's canvas and relative functions.
Look at that:
http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
Maybe also you have to look at how a MAP is built with HTML 5
After tinkering, and lots of google searching, a quick search for "jquery infinite drag" returned this result:
http://ianli.com/infinitedrag/
I managed to use the function call provided when each cell is created, to gather map data from the database (ajax) and create the cells as needed.
http://mc1.empirebattles.com/map/jquery_map.html
I REALLY like the way its working so far, except that if i want to be able to click on anything under the map (for actions and such), the click event is called whenever i release the click for dragging the map around.... i've tried jquery's UI doubleclick, but it appears this plugin takes control as soon as double click is called
Anyways, incase anyone else needs something similar to this, this solution has helped me lots!

Export div content to image

Currently I'm working on a project in which user of website can design a giftwall by drag and drop of gifts. Drag, drop and sorting works perfect and I'm able to store generated giftwall into database. On recipient side system lists all the gift images in the same sequence sender sent so it visually looks like a giftwall. I want to allow users to store this giftwall into a single image so they can store their giftwalls into image album. In current system it lists all individual gifts into a individual div resided in main wrapper div. How can I export this wrapper div to image so it looks same as HTML. Any help will really be appreciated. Waiting for reply.
Thanks!
I don't know if there is a way by using pure javascript, but you can generate the image on your server and send it back.
I have never heard of saving browser's viewport to an image file via JS. I think it's only possible vie creating SVG or using HTML5 canvas.
I asked exactly the same thing a while back.
HTML div to screenshot?
The conclusion is... it is not possible with JS. Questionably possible from PHP also.
Use can use an online service for screen capture, like browsershots, but its not in real-time, and doesn't render everything well.
I used a workaround for my situation.
Recreated all the DOM/HTML elements which create the image (load parameters form database, and generate the DOM). Wrap everything in one container div, and zoom it out to the size you need.
I know, not the prettiest solution, but the only solution I could get to work.
Using <canvas> you can create image that will looks similar to how it looks on the page. Try it this way:
Get the size of wrapper <div> and create the same canvas element. Then get the position of each image in the div wrapper and draw that image on canvas at the same position with the same size.
Things may be harder if you need to draw additional controls, like button or textbox.
All modern desktop browsers suport <canvas> now.
You can either use html2canvas, which isn't perfect yet. Or store browser offsets of elements in div and then with GD or ImageMagick combine them into an image
Maybe this could be of use: http://html2canvas.hertzen.com/

Saving Div Contents or Canvas as Image

I have read a few similar questions and answers, but none completely address my issue.
Here is My Scenario:
I have what is similar to a tinyMCE (a home-brew version though) kind of editor. It lets users enter some text, and an image or two, etc. I have code that takes the items in there and renders them into a smaller div (what is essentially a thumbnail) in real time.
Here is What I Want to Do
Ultimately, the user may want to use their 'page' somewhere else, so I would like to let them go to a screen, view thumbnails of each page, and pick one.
Here is the Problem
Obviously, I could just use the same thumbnail code to render each page thumbnail. However, it can be bandwidth intensive (each page could have several images, not to mention the calculation would have to be performed many times - we are talking perhaps 40 to 50 thumbnails on a preview page).
So, I wanted to try to take the thumbnail div, and somehow create a png or jpg when they save the page in the editor (so the code for the page, and also a thumbnail image), and push it up to my PHP script to save the image to the server.
My first thought was that maybe canvas could do that, but there is the issue of translating the text and images onto the canvas first, which may or may not be possible.
So there it is. I am interested in any and all options, including commercial libraries if available that will do this -- only thing is, would like it to be in javascript.
You may want to look at:
http://html2canvas.hertzen.com/
A similar question was already asked:
Screen Grab with PHP and/or Javascript?

how can I use javascript or php to determine when images are loaded if image tags are dynamically created from database?

I have a page that's very image-intensive. This is by client request - it's a list of merchants with a logo for each one. The list is quite long (over 500), and yes - the client insists on displaying all of them. We do have an ajax typeahead search to help users find what they're looking for without scrolling, so it's not a total disaster.
Here's the issue: the client is just now realizing that it takes a long time to load this page because of all the logos. Even if each one is only a few kb, it still adds up pretty quickly. He's now decided he wants a progress bar to display while the images are loading. I've never done that before, so I starting looking around, and most of the ones I've seen rely on getting an array of img tags and looping through to check the complete property. The problem I'm having (at least I think this is what's causing the problem) is that the image tags are generated by a database query, and I think the javascript to get the image array is loading before the image tags are finished loading. Obviously this isn't an issue on pages where the images are hard-coded.
Can anyone point me in the right direction of how I can implement a progress bar on img tags that get loaded dynamically? My site is written in PHP, so I'm perfectly happy to do something server-side if that would work better.
As pretty much everyone here has noted, this is a nasty problem to have to solve. Accordingly, I propose sidestepping the technical components of it and addressing only the human ones.
Leave everything almost exactly as it is. All you have to do is find or make a throbber (I use http://ajaxload.info/ and it couldn't be easier), and use it as the background image for a CSS selector that only applies to the logos on the page.
Users (and clients who make unreasonable requests!) are far more frustrated by a lack of responsiveness than they are by things taking time. This quick gimmicky fix might be just enough to coax site users to perceive the problem more as the latter than as the former.
CSS Sprites will definitely be a good start in your case. If you got 500 spearate images on one page, then browser will have to start 500 new connections to fetch them, and unfortunately, concurrent connections will be around 20 or something, so... it is not good.
CSS Sprites from css-tricks.com
I'd suggest pre-making and caching of the logos (or their various states), as your own hunch is that the main bottleneck is that "the image tags are generated by a database query". Is this at all possible?
It's better to store a few states or whatever with a naming scheme that makes it possible to fetch the right image, than regenerating them on-the-fly each time. Of course, you'll need a proper cache handling mechanism, so it's not like an easy task, but more often than not, your hunch is helping you in the right direction.
If you're able to boil it down to a few static files per logo, you could also consider using a CDN and/or multiple subdomains, as Michael Mao suggests.
I haven't tested this but something like this might work (its jQuery)
<?php // Do your select image stuff from here ?>
<html>
<head></head>
<body>
<script type="text/javascript">
$(document).ready(function () {
var images = <?php echo json_encode($images); ?>;
$.each(images, function(i, image) {
$(new Image()).load(function () {
$('body').append(this);
alert('Loaded '+i+' out of '+images.length);
}).attr('src', image);
})
});
</script>
Since you already have a javascript search to get people to specific listings faster, how about loading a placeholder static image for all logos and then replacing the placeholder with the correct logos on an as-needed basis? "As-needed" could be determined by JavasScript calculation of window position and any typed input.
Do your just-in-time image loading from multiple subdomain masks to parallelize requests and you should be able to pop the images up somewhat quickly as-needed without bogging down the page by loading unnecessary images.
It's not pretty, but neither is the client's request.
Edit: As far as a progress bar goes, when you determine a window location (or typed-input location), determine how many listings will be in-view, and how many listings to buffer above and below the view. Then you'll have a total number of listings and you can update a JavaScript/HTML progressbar as you dynamically replace the logos within that range.
It would be much easier to answer the question if I could see the complete code but I can remember doing something remotely similar and I ended up using a custom JavaScript object. You could perhaps start with an object like this somewhere in the head of your app:
function Iterator() {
var counter = 0;
this.images = 215; // This number comes from the DB and gives you a total number of images
this.progress = counter / this.images
this.hasMore = function() { counter < this.images }
this.getPicture = function() {
// send a request to the server using counter as a parameter
// upon receiving this request the server should load only ONE image (LIMIT=1 in SQL)
// with OFFSET equal to the value of "counter"
// when the image loads (use whatever JS framework you need for that),
// we increment the counter:
counter++;
}
this.loadPictures = function() {
while this.hasMore() {
this.getPicture()
// You can do something with the "progress" attribute here, to be visualizad by your progress bar
}
}
);
You sure need to instantiate the Iterator object on body load and have it execute the "loadPictures" function.
Please let me know if you have any problems implementing that.
Here's a javascript-only solution that shouldn't require any modification to your server-side code. Using jquery:
$(document).ready(function() {
var loadedSoFar = 0;
//use jquery to get all image tags you want.
//The totalImgs is used to calculate percent and is the length of the jquery array
var totalImgs = $("#imgHolder img").each(function(i, img) {
//if this image has already loaded, add it to loadedSoFar.
if (img.complete)
loadedSoFar++;
else {
//otherwise add a load event for the image.
$(img).load(function() {
loadedSoFar++;
console.log("complete: " + (loadedSoFar / totalImgs * 100) + "%");
});
}
}).length;
});
I wrote this assuming all the images are already in the dom when the document.ready is called. If it is not, move this to a function and call it after the img tags are loaded into the dom from the server (via ajax request for instance).
Basically all it does is find all the imgs in imgHolder (modify the selector to match your situation), and wire the load event so it can update the loadedSoFar count. If the image has already loaded by the time this script runs, the load event would never fire, so increment the loadedSoFar counter right away. The number of total images that need to be loaded will be the length of the jquery object array returned by the selector.
I'll leave it to you to write a progress bar, but I do recommend this plugin: http://t.wits.sg/jquery-progress-bar/
I'd definitely try to avoid the progress bar -- you're going to really struggle with it.
If you really must do it, probably the best you can hope for is to fake it - ie have it show progress on a given amount of time, which you'd set as an approximation of the actual time it takes to load the page. Not foolproof but far easier than trying to actually time the loading progress.
Don't forget also that the progress bar itself will add to the loading time. And you'll need to have the code for it embedded in your actual HTML code; if it's in an external javascript file it could itself be subject to loading delays, which would make the whole excersise pointless.
So as I say, it's probably not worth the effort. What would be worth the effort would be to try to reduce the loading time. If it's noticable enough that you're considering a progress bar then there's something seriously wrong.
There are a whole stack to techniques for speeding up site loading times; it's a whole topic on its own. But I'll try to give you a few pointers. I suggest you also take some time googling for additional and follow-up information, though.
Image optimisation. If you haven't done so already, run all your images through an optimising program. You may find that you can reduce file sizes and thus load-times significantly.
CSS Sprites. One of the main causes of slow loading times is having too many separate HTTP requests. Since a browser can only load a given number of files at once, any files over that number will have to wait till others have finished before they can even begin loading. CSS sprites solves this by combining a number of images into a single file and using CSS to display only the relevant part of it in each spot. This is typically used for groups of related images.
Lazy Load. There is a jQuery plugin called LazyLoad which tells your page to load images only as they are needed. Images that are off the bottom of the viewable page are deferred until the user starts scrolling the page. This means that the images that are visible immediately are loaded first, making the page as a whole appear to load more quickly.
That'll do for now. There's loads more, of course, but all I'm really trying to say is: Optimise to get rid of the speed issue rather than trying to cobble together a band aid solution.
Hope that helps.
there are different ways to speedup image loading especially when you have a lot of them
Sprite - Use sprite where you group a number of images together and use the css background property (FACT: one big image better speed than multiple requested images).
Use the <image/> tag properly. You can add the lowsrc="" attribute to show a low resolution image until the real image aka src="" attribute is fully loaded
Use the ajax, although you may have 500+ images users will never see the full list. So you can load 6 at a time (or Nth at a time) when the document is fully loaded you can add the rest that way u can speed up the loading time as the user will only see some images and by the time they click next set of images they would have been loaded (or wait less) better yet to save broadband only use the ajax when required aka only when they click next or scroll down auto load new images. (look at google images and ajax used while scralling)

Categories