hey guys, i am working on a project and it needs user to upload image. i dont want to bug the user by restricting the file size, instead i want to auto resize the image when user upload from his system and then after resizing i want to upload that file to server. can anyone help me in this/
Jarrod Oberto made a great resizing library, while it’s starting to show its age this php resizing lib still is good.
Here’s a link to it: http://www.jarrodoberto.com/articles/2011/09/image-resizing-made-easy-with-php
I would recommend using this or a similar one, rather that trying to create your own (unless you’re a super geek when it comes to math).
Well, I agree with Strider64 that a library is handy if you are planning to do a lot of graphics work.
But, to resample images that are uploaded by a user of your site to a set size is very simple in PHP.
It usually only takes a few lines of code. But, before explaining how to do this, I am wondering why
you need to do it? Normally, when you display any image on your site, it can be optionally resized in
the HTML line of code where the image is displayed. I normally just limit the size of the upload to a
reasonable limit.
Now, if you want to resize an image in PHP, you can use it’s built-in graphics functions. Here are the lines
that will take an image and resize it to 100 pixels x 100 pixels. You can look at these functions if you need
to use other options. You can basically do most anything that Photoshop can do, but, some commands are
very tricky. Resizing is simple enough…
[php]
// The file
$filename = ‘test.jpg’; // Whatever you are using for testing this routine…
// Get dimensions of old image
list($width, $height) = getimagesize($filename);
// Resample
$new_image = imagecreatetruecolor(100, 100); // 100 is new width and height…
$old_image = imagecreatefromjpeg($filename);
imagecopyresampled($new_image, $old_image, 0, 0, 0, 0, 100, 100, $width, $height);
// Output
imagejpeg($new_image, “…/images/new_test_image.jpg”, 100);
// Destroy the temporary pictures from memory to free up the server ram…
imagedestroy($new_image);
imagedestroy($old_image);
[/php]
There are several things to mention. First, a user can upload GIF’s, PNG’s or JPG’s. This sample is just for
JPG’s. You can add in the others with just a few new lines of code. Next, in using the resample function,
you create two images in memory. These can eat up memory quickly. You need the last two lines to make
sure they are removed from memory after using them. If you have questions after testing this, ask them
here and we can help you. Please note that this is just a simple routine. It does not do all of the other
functions that are available in a full fledge graphics library. But, I have used this on many sites for making
profile pictures resized to a set limit. It has always done well for me. Good luck!