JavaScript image resize slowness - php

A site I am working on has a lot of images that are pulled from a database. The dimensions of the images are not consistent and I am trying to display them in uniformly sized boxes (divs). I do not know the dimensions of any of the images but I can retrieve them with:
document.getElementById( myImage ).width
document.getElementById( myImage ).height
After this I do my tests to see how to resize images to fit the uniform boxes. Finally I set the effects with:
document.getElementById( myImage ).width = theNewWidth
document.getElementById( myImage ).height = theNewHeight
This function is only called once per image by using onload="resizingFunction( imgId );" in the img tag. It takes about 1-2 seconds for every image in the database to complete this function and the function is never run for any of those images again. Despite never running again, the site runs significantly slower if I use this function. After googling I tried adding:
document.getElementById( myImage ).removeAttribute("width")
document.getElementById( myImage ).removeAttribute("height")
Before setting the new width and height. This did improve the speed but it is still slower than if I had not resized the images. Again, just for clarification, each image is resized one time after it has been loaded but for some reason this still slows down the site.
Images are created by being PHP echoed into JavaScript. This is necessary because they need information from the database (PHP), and the JavaScript places them inside the correct box (div). Here is the creation of image code:
echo "\t\t\tdocument.getElementById('gBox".$i."').innerHTML = '<img onload=\"image_applyToGrid(".$i.");\" id=\"img".$i."\" style=\"left:0; top:0;\" src=\"'+gBoxes[".$i."].imgPath+'\"/>';\n";
Here is the image resizing function that images call once onload:
function image_applyToGrid(inId) {
inIdImage = document.getElementById("img"+inId);
var imgW = inIdImage.width;
var imgH = inIdImage.height;
if (imgW > imgH) {
var proportions = imgW/imgH;
imgH = gridUnit;
imgW = gridUnit*proportions;
inIdImage.style.left = -((imgW-gridUnit)>>1)+"px";
}
else {
var proportions = imgH/imgW;
imgW = gridUnit;
imgH = gridUnit*proportions;
inIdImage.style.top = -((imgH-gridUnit)>>1)+"px";
}
inIdImage.removeAttribute("width");
inIdImage.removeAttribute("height");
inIdImage.width = imgW;
inIdImage.height = imgH;
}

Resizing images with Javascript is generally not an ideal approach. You are consuming all of the bandwidth to send the full size images across the web and then scaling them down. A better way would be to pull the images from your image store and resize them server side. Then store the result in a server side cache so you can provide all of your client requests with the optimized images. No need to over think the concept of cache here, in this case it could be as simple as a directory or a new column in your database. (FWIW, I prefer not to store binary data in databases but that's probably another discussion)
See: http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/

The images are probably much too large. I would suggest preparing the images for web use. Google "optimizing images for web" for some ideas on how to do this.

It's bad practice to take full-size images and load the entire image at different dimensions. Consider having thumbnails generated and placed on the page.
If you have a 2500x2500 image that you're just setting the height and width to 500x500, the entire 2500x2500 image is still having to be loaded.

Related

optimized way to scale image

I have the following function that runs thought about 25 times and delays the site's load time by 10 seconds or more. What the code is essentially doing is working out the height when the image's width is scaled down or up to 310px. Any suggestions on how I could improve my code or suggest another option? Maybe jQuery might be better for this?
function img_height($image){
$inputwidth = 310;
list($width,$height) = getimagesize($image);
if($width !== $inputwidth){
$outputheight = ($inputwidth * $height)/ $width;
}elseif($width == $inputwidth){
$outputheight = $height;
}
return 'style="height:'.$outputheight.'px;" ';
}
#Enigmo - I have worked a lot with image loading and dynamically changing sizes. You really cannot make a big difference in the loading time using PHP. I would suggest you to use AJAX and preload the images or do a lazy loading. That way your site gets loaded first and then the images keep showing up as and when they are loaded.
I would suggest storing images sizes alongside with the image names in some db structure (cache). Then, you would know already all the sizes and your site would work blazingly fast.
you can simply use jquery stuff to do this stuff as this will be getting fired at client browser and not making any load/processing on server side. also jquery is faster than php processing also

resize external images from other websites before loading them?

Iam working on a project , which involves fetching images from various websites and displaying a Thumnail or resized version of orignal image.
As i will be fetching many images at time , this takes more time , As Orignal image files will be loaded.
What i need is given an image url , i need resized version of that image file? So that i need not download the Large orignal image file...
for example : orignal image : 500X800 some 500kb
what i need is : 100X150 some 100kb image file..
Is it possible using Jquery? OR PHP?
Are their any functions like imagecopyresampled(PHP) in Jquery or any plugins?
Well, the big file needs to be downloaded at one point to create the thumbnail.
What you can do, through JQuery, is ask your server for the thumbnail, the server downloads the file, creates the thumbnail and sends back to the client the URL of the thumbnail when the resizing is done. This way, the client will gradually receive thumbnails as they are ready.
Edit After experimenting a bit, I found out that as soon as an img requests a picture, even if you dynamically remove its src attribute, the download continue.
So I decided to write a sample code (there's not much validation and it only works for jpeg, adding the other types would be really easy though). The solution is divided in 3 parts:
HTML
First, I used an empty div with some specific attributes to let jQuery what to load. I need to apologize to Nuria Oliver, she had the first "big picture" I could find on the net. So, here's a sample div:
<div class="thumbnail" data-source="http://www.nuriaoliver.com/pics/nuria1.jpg" data-thumbnail-width="100" data-thumbnail-height= "200"/></div>
I use thumbnail as class to be able to find easily the divs I want. The other data parameters allow me to configure the thumbnail with the source, width and height.
JavaScript / jQuery
Now, we need to locate all these divs requesting thumbnails... using jQuery it is pretty easy. We extract all the data settings and push them in an array. We then feed a PHP page with the query and wait for the response. While doing so, I'm filling the div with some HTML showing the "progress"
<script type="text/javascript">
$(".thumbnail").each(function() {
var img = $(this);
var thumbnailWidth = img.data("thumbnail-width");
var thumbnailHeight = img.data("thumbnail-height");
var thumbnailSource = img.data("source");
var innerDiv = "<div style='width:" + thumbnailWidth + "px; height:" + thumbnailHeight + "px'>Loading Thumbnail<br><img src='loading.gif'></div>";
img.html(innerDiv); // replace with placeholder
var thumbnailParams = {};
thumbnailParams['src'] = thumbnailSource;
thumbnailParams['width'] = thumbnailWidth;
thumbnailParams['height'] = thumbnailHeight;
$.ajax({
url: "imageloader.php",
data: thumbnailParams,
success: function(data) {
img.html("<img src='" + data + "'>");
},
});
})
</script>
PHP
On the PHP side of things, I do a quick test to see if the picture has already been cached (I'm only using the file name, this should be more complicated but it was just to give you an example) otherwise I download the picture, resize it, store it in a thumbnail folder and return the path to jQuery:
<?php
$url = $_GET["src"];
$width = $_GET["width"];
$height = $_GET["height"];
$filename = "thumbnail/" . basename($url);
if(is_file($filename)) // File is already cached
{
echo $filename;
exit;
}
// for now only assume JPG, but checking the extention should be easy to support other types
file_put_contents($filename, file_get_contents($url)); // download large picture
list($originalWidth, $originalHeight) = getimagesize($filename);
$original = imagecreatefromjpeg($filename); // load original file
$thumbnail = imagecreatetruecolor($width, $height); // create thumbnail
imagecopyresized($thumbnail, $original, 0, 0, 0, 0, $width, $height, $originalWidth, $originalHeight); // copy the thumbnail
imagedestroy($original);
imagejpeg($thumbnail, $filename); // overwrite existing file
imagedestroy($thumbnail);
echo $filename;
Browser
So, what does it do exactly? In the Browser, when I open the page I first see:
And as soon as the server is done processing the image, it gets updated automatically to:
Which is a thumbnail version, 100x200 of our original picture.
I hope this covers everything you needed!
PHP Thumb is a good plugin it worked for me and easy to operate.
And the best part is there are many options to select about the output file like its quality, max width for potrait images , max width for landscape images etc..
And we can set permissions like block off server requests, block off domain thumbnails.. etc
Note: this was actually posted by someone , as an answer to this question..But it was deleted.So iam reposting it, as it was useful.
for this to work you need to do some actual image processing which you cant do with js, so some server side language is needed.PHP is an option
If you are not interesting in obfuscating the image source, you may very well rely on an external tool like http://images.weserv.nl/ which takes an original image and allows you to request it in a different size.
If you end up not relying on a global CDN, at least sort out proper caching. Last thing you want to do is resize the same image over and over again for subsequent identical requests - any benefit of image's lower size will probably be negated by processing time.

How does the three20 gallery load images?

On my server, I have three files per image.
A thumbnail file, which is cropped to 128 by 128.
A small file, which I aspect fit to a max of 160 by 240.
A large file, which I aspect fit to a max of 960 by 540.
My method for returning these URLs to three20's gallery looks like this:
- (NSString*)URLForVersion:(TTPhotoVersion)version {
switch (version) {
case TTPhotoVersionLarge:
return _urlLarge;
case TTPhotoVersionMedium:
return _urlSmall;
case TTPhotoVersionSmall:
return _urlSmall;
case TTPhotoVersionThumbnail:
return _urlThumb;
default:
return nil;
}
}
After having logged when these various values are called, the following happens:
When the thumbnail page loads, only thumbnails are called (as expected)
When an image is tapped, the thumbnail appears, and not the small image.
After that thumbnail appears, the large image is loaded directly (without the small image being displayed).
What I desire to happen is the following
This is the same (thumbnails load as expected on the main page)
When the image is tapped, the small image is loaded first
Then after that, the large image is loaded.
Or, the following
Thumbnails
Straight to large image.
The problem with the thumb, is that I crop it so it is a square.
This means that when a thumbnail image is displayed in the main viewer (after thumb was tapped), it is oversized, and when the large image loads, it immediately scales down to fit.
That looks really bad, and to me, it would make far more sense if it loaded the thumbs in the thumbnail view, and then the small image followed by the large image in the detail view.
Does anyone have any suggestions on how to fix this?
Is the best way simply to make the thumbs the same aspect ratio?
I would appreciate any advice on this issue
Looking at the three20 source I can see that TTPhotoView loads the preview image using the following logic:
- (BOOL)loadPreview:(BOOL)fromNetwork {
if (![self loadVersion:TTPhotoVersionLarge fromNetwork:NO]) {
if (![self loadVersion:TTPhotoVersionSmall fromNetwork:NO]) {
if (![self loadVersion:TTPhotoVersionThumbnail fromNetwork:fromNetwork]) {
return NO;
}
}
}
return YES;
}
The problem is that as your small image is on the server and not locally the code skips the image and uses the Thumbnail for the preview.
I would suggest that your best solution would be to edit the thumbnails so that they have the same aspect ratio as the large images. This is what the developer of this class seems to have expected!
I think you have three ways to go here:
modify the actual loadPreview implementation from TTPhotoView so that it implements the logic you want (i.e., allowing loading the small version from the network);
subclass TTPhotoView and override loadPreview to the same effect as above;
pre-cache the small versions of your photos; i.e, modify/subclass TTThumbView so that when TTPhotoVersionThumbnail is set, it pre-caches the TTPhotoVersionSmall version; in this case, being the image already present locally, loadPreview will find it without needing to go out for the network; as an aside, you might do the pre-caching at any time that you see fit for your app; to pre-cache the image you would create a TTButton with the proper URL (this will both deal with the TTURLRequest and the cache for you);
otherwise, you could do the crop on-the-fly from the small version to the thumbnail version by using this UIImage category; in this case you should also tweak the way your TTThumbView is drawn by overriding its imageForCurrentState method so that the cropping is applied when necessary. Again, either you modify directly TTThumbView or you subclass it; alternatively, you can define layoutSubviews in your photo view controller and modify there each of the TTThumbViews you have:
- (void)layoutSubviews {
[super layoutSubviews];
for (NSInteger i = 0; i < _thumbViews.count; ++i) {
TTThumbView* tv = [_thumbViews objectAtIndex:i];
[tv contentForCurrentState].image = <cropped image>;
If you prefer not using the private method contentForCurrentState, you could simply do:
[tv addSubview:<cropped image>];
As you can see, each option will have its pros and cons; 1 and 2 are the easiest to implement, but the small version will be loaded from the network so it could add some delay; the same holds true for 4, although the approach is different; 3 gives you the most responsive implementation (no additional delay from the network, since you pre-cache), but it is possibly the most complex solution to implement (either you download the image and cache it yourself, or use TTButton to do that for you, which is kind of not very "clean").
Anyway, hope it helps.

Is that possible to display image thumbnail without uploading it to the server?

I want let user to upload images to server add some info (like description, tags) about each image.I use Uploadify to upload multiple images.
I wonder if it is possible to show thumbnails of the images (while the user enters the additional info about each image) before the images are actually uploaded to the server.
I want user to have the following experience:
Select multiple image files
Immediately after that enter additional information about each image while seeing images thumbnails
Press Upload Files button to upload images to server, and go to drink coffee...
I found this script, but I think it also uploads the file before displaying the image thumbnail.
I would appreciate any help !
If you could enforce an HTML 5 capable browser you could use the file-api
Example: http://html5demos.com/file-api
Sure it is possible. Use the FileReader object to get a data URL (or use File.url if you are sure the Client implements it.) and assign it to an new Image()object. Then you can insert the image into DOM.
As an alternative to the standard-based HTML5 APIs, you can use a plugin such as Flash or Browserplus.
There is actually a ready-made application which might do exactly what you want. It's called Plupload. You can upload your files / images using a variety of "runtimes", and do client-side image resizing before uploading. I guess you can hook a thumbnail preview somewhere in there, in certain runtimes.
Otherwise, you can try building what you want from scratch, using the HTML5 / Gears / BrowserPlus / etc. APIs.
I'm pretty sure flash and java can both do it. Flash would require certain (obvious) security precautions (ie, you can do this for any file, it must be selected by the user).
Meanwhile java would show a security popup.
Xavier posted this solution on another thread, and I tried to improove it to work with multiple file inputs. I hope it helps.
$("body").on('change', 'input:file', function(e){
for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
var file = e.originalEvent.srcElement.files[i];
var img = document.createElement("img");
var reader = new FileReader();
reader.onloadend = function() {
img.src = reader.result;
}
img.width = "50";
reader.readAsDataURL(file);
if($(this).next().hasClass('image_place')){
$(this).next('.image_place').html('').append(img);
}else {
$(this).after('<div class="image_place"></div>');
$(this).next('.image_place').append(img);
}
}
});
It scans all file inputs in the document body and reads the image using the FileReader api. If it finds any images, it creates a div called "image_place" where he puts the image. If there's already a image inside, the script replaces the image.

Use face from an image for postcard (see screenshot)

I am looking to build an app similar to santayourself (facebook application) a screenshot below
The application will accept a photo and then the users can move it with controls for zoom and rotate and moving image right, left, up and down. Then once the face is as required then the user can click save to save the image on the server (php, apache, linux).
Any recommendations on how to go about this project? I guess a javascript solution will be better. Any suggestions welcome.
javascript AND php GD-library would do it - most of the things described above can be done w javascript alone. The fastest way to do this would be to have the santa mask done w a transparent png absolutely placed over a simalarly placed client photo that is however placed in a div the same size as the mask with overflow set to hidden. Since the client phot is absolute within the div it can be moved around and its size can be manipulated by the user through some mechanism as shown above. However - rotation will be a bitch and here you will have to use php gd-library or image majik (personally i would dump rotation). This is a simple-ish job but time consuming - the user-interface to image manipulation is tricky tho. If the output for this is for print-from-screen i would not bother w further server-side manipulation, but rather just store the image to mask positional relationship (1/2 kb) of data...
yep. javascript is the way to go about interactive things like this. I can see this easily being done with a simple script and some PNGs (though you might have to do something creative for the rotation). PHP would only be needed for saving.
EDIT: Actually, now that I think of it, a HTML 5 canvas approach would be best. It's got lots of transformation and pixel-manipulation methods, and can even save the image client-side! Remember, though that HTML 5 is not supported in all browsers (basically everything except IE).
(HTML 5 Canvas Spec)
The drawImage method is what you're looking for:
(I quote from spec)
void drawImage(in HTMLImageElement image, in float dx, in float dy, in optional float dw, in float dh);
So, your HTML would have a canvas element that draws the user's picture:
<canvas id="canvasElement" width="xx px" height="xx px">
<!-- What to display in browsers that don't support canvas -->
<p>Your browser doesn't support canvas</p>
</canvas>
Then, your javascript:
var view;
var context;
var userPhoto=new Image;
userPhoto.src="uploaded.jpg";
// Update these with UI settings
var position = {x:x, y:y};
var scale;
var rotation;
function init() {
// Run this once at the loading of your page
view = document.getElementById("canvasElement");
context = view.getContext("2d");
}
function update() {
// Run this every time you want the picture size, position, rotation updated
context.clearRect(0, 0, view.width, view.height);
// Scale X and Y
context.scale( scale, scale );
// Rotate (convert degrees to radians)
context.rotate( rotation / 3.14159 * 180 )
// Draw the image at X and Y
context.drawImage( userPhoto, position.x, position.y )
}
HTML 5 Canvas is very powerful, so there's tons of other things you can do to your image if you go this direction. However, another viable solution would be to use flash, which is supported everywhere — but I recommend HTML 5 as it is the way of the future (Steve Jobs: Thoughts on Flash).
Have a look at the jCrop library (jQuery), you may be able to tweak it enough to do what you want to do.
http://deepliquid.com/content/Jcrop.html (they obviously supply a few demos)

Categories