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.
Related
I have 2 different scripts for handling images:
The first one is a watermark script for watermarking images on the fly:
$imgpath=$_REQUEST['filename'];
header('content-type: image/jpeg');
$watermarkfile="assets/img/logo_variations/logo_watermark_75.png";
$watermark = imagecreatefrompng($watermarkfile);
list($watermark_width,$watermark_height) = getimagesize($watermarkfile);
$image = imagecreatefromjpeg($imgpath);
$size = getimagesize($imgpath);
$dest_x = ($size[0] - $watermark_width)/2;
$dest_y = ($size[1] - $watermark_height)/2;
imagecopy($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height);
imagejpeg($image);
imagedestroy($image);
imagedestroy($watermark);
So the image URL for a watermarked image is: http://example.com/watermark.php?filename=assets/img/temp/temp_share.jpg or since I'm using mod_rewrite to "pretty up" my URL: http://example.com/watermark/assets/img/temp/temp_share.jpg.
Works like a charm and my reason for doing so like this is because this is on a modeling website where I want to display the images without watermarks but I use a jquery script to change the image source of the image gets right clicked(assuming a user is trying to save the image).
The script only changes the source of any image with a class of img-protected.
I've written it to ignore any image with watermark in the URL so that it doesn't try to change the already watermarked image which would result in a url like: http://example.com/watermark/watermark/img.jpg which would result in a broken image. The other part is written to remove http://example.com from the original source so I don't end up with http://example.com/watermark/http://example.com/img.jpg.
$('.img-protected').on('mousedown', function (event) {
if (event.which == 3) {
if(this.src.indexOf("watermark") > -1) {
return false;
}
else {
src = this.src.replace('http://example.com/','');
this.src = 'http://example.com/watermark/' + src;
}
}
});
All of this works exceptionally well until I added another image handling script:
I'm using TimThumb.php which is an on the fly image resize script I use for creating gallery icons instead of uploading an icon and a full size image(this is how I wish to keep doing so as well).
The problem I am facing is this:
If I have an image that is being turned into a thumbnail using TimThumb.php which I renamed to thumb.php on my server the URL is http://example.com/thumb.php?src=gallery/goth/industrial_brick/5361ae7de9404.jpg&w=350&h=500a=c&s=1&f=11 which gives me an icon for 5361ae7de9404.jpg.
All of my icons have a class of img-protected which means on right click the above URL is going to be changed to the watermarked one.
This is where it fails.
The outputed URL when right clicked is http://example.com/watermark/http://www.example.com/thumb.php?src=gallery/goth/industrial_brick/5361ae7de9404.jpg&w=350&h=500a=c&s=1&f=11 which results in a broken image.
I manually tried making the URL into http://example.com/watermark/thumb.php?src=gallery/goth/industrial_brick/5361ae7de9404.jpg&w=350&h=500a=c&s=1&f=11 to see if that would change anything but it still results in a broken image.
What I need is to be able to also watermark the generated icons from thumb.php using watermark.php.
Is there a way to combine these two scripts or a workaround to make this work?
I'm at a complete loss here.
EDIT: I am fully aware that advanced users can still acquire the non watermarked image since it's already been downloaded to there device, but I don't expect a high volume of users to visit this particular website as this is simply a local models portfolio.
I am using php to rotate a photo on server. When I click a button 'rotate' I use ajax to load php page, perform rotation and refresh div with new image.
Everything works and the image has been rotated with the correct dimensions but the image itself hasn't rotated. If i hit f5 to refresh page, the image is displayed corrected. Does anyone know why the image isn't displayed correctly before refreshing.
$photo_path= $result['photo_path'];
$src = imagecreatefromjpeg($photo_path);
$rotate = imagerotate($src, 90, 0);
#unlink($photo_path);
imagejpeg($rotate,$photo_path);
imagedestroy($src);
imagedestroy($rotate);
Any ideas?
try this,
$file="myimage.jpg";
$file1 = imagecreatefromjpeg($file);
$file2 = imagerotate($file1, $degrees, 0);
file_put_contents("newimage.jpg",$file2);
Maybe use JavaScript as this is a client side problem.
Update: this is very basic but test it out and see if it works;
<script>
function changeImage(o){
o.src = '//' + (new Date()).getTime(); // time to help stop caching
}
</script>
<img src="//" onclick="changeImage(this)" />
I managed to solve it. Thanks for all the help.
What i did was just give the photo a new file name and update mysql table. Must have something to do with the image being cached and I was keeping the new rotated file with the same file name.
Thanks again.
You can add a question mark and a random number after the extension of the file and this makes the user browser ignore the local cache, and reload the file. For example:
myimage.png?789 <- Random number
I have the following scenario. I have about around 600 pictures. Most of theme have in bottom a logo which should be cut it out because branding issue, but not all of theme.(with ftp and photoshop would be a challange)The approach what I was thinking about I list all of my images form folders and I add to theme a hyperlink which should fire on a method class which cuts out 57px from bottom, because the image listing limited to height and width, after cutting should not be present on the page
the url looks like
cut.php?target=http://example.com/hideit/2012/03/myimage.jpg
I want to reset the get parameter after execution to avoid problems on page refresh while would cut again from that image the defined pixels. I was trying the following
function cutAndsave($jpg){
$folder = explode('/', $jpg);
$path = 'I:\\xampp\\htdocs\\hideit\\'. $folder[4]. '\\'. $folder[5] .'\\'.$folder[6] ;
list($width, $height) = getimagesize($jpg);
$offset_x = 0;
$offset_y = 0;
$new_height = $height - 57;
$new_width = $width;
$image = imagecreatefromjpeg($jpg);
$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopy($new_image, $image, 0, 0, $offset_x, $offset_y, $width, $height);
header('Content-Type: image/jpeg');
imagejpeg($new_image,$path, 90);
header("Location: /cat.php/");
die();
}
but the last header call won't work in my case
Your concrete problem at hand is that you're trying to send an HTTP header after you output an image. HTTP headers can only be sent before any content; they're headers after all.
The bigger problem is that the idea is nonsense.
The client requests a URL, example.com/image.php?id=42.jpg. You may think of this URL as a filename. The image is identified by the filename/URL. Different URL, different image. It also doesn't matter that this is a PHP script and not a physical file on a hard disk somewhere, that detail is irrelevant to the client. The client requests the URL and receives an image in return, that's all that matters. Whether the image is just read as is from a data storage, is resized by a script on the fly, is live drawn by unicorns behind the scenes, that all doesn't matter; it's an implementation detail.
URL request, response. That's the important concept you need to grok for working with web servers.
As such, "resetting URL parameters" is pointless. You can't do that. You can redirect the client to a different URL, but that's a different file/URL then. If you want the client to get the image, you respond with an image whenever the client asks for the URL. If the user refreshes the page so the client requests the URL again, so be it.
If you do not want to do the image cutting again and again, cache the resized file. In code, check:
Oh, somebody's requesting image #42.
Do I have a resized version of image #42 already?
If no, create a resized version and save it somewhere.
Serve the resized image #42.
On top of that you can set HTTP headers that influence the client's caching behavior, so the client will keep the image in its cache and not request it again every time.
In case it's also as simple as not overwriting the original. Always keep the original intact, the cut version should be a copy of it. You can either generate that copy as described above, or when the original is uploaded. But don't change the behavior of a URL depending on whether you have already processed the image or not.
You have an error in line header("Location: /cat.php/");
It should be
header("Location: /cut.php");
if you just want to go back to last page.
If you want to additionally show your image you can do
header("Location: /cut.php?show=$path")
and then do a script in your file which prints an <img> tag.
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.
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.