Please help with the php code to upload an image. The image should be compressed while uploading without disturbing its resolution. Also, the image should be resized in 500 x 500 px. Any assistance will be appreciated. Thanks in advance
Asked
Active
Viewed 8,775 times
-2
-
1have a look here http://www.w3bees.com/2013/03/resize-image-while-upload-using-php.html – rocky Aug 17 '15 at 05:36
-
dupe of a bizzilion questions – Aug 17 '15 at 05:36
-
possible duplicate of [Resize image on upload php](http://stackoverflow.com/questions/4612289/resize-image-on-upload-php) – Venugopal Madathil Aug 17 '15 at 05:40
-
Soooooo.. Welcome to SO, read the FAQ before asking a question etc, add code of what you've tried bla bla bla, better luck next time . – dbf Sep 08 '16 at 09:13
1 Answers
1
function resize_image($file, $width, $height) {
list($w, $h) = getimagesize($file);
/* calculate new image size with ratio */
$ratio = max($width/$w, $height/$h);
$h = ceil($height / $ratio);
$x = ($w - $width / $ratio) / 2;
$w = ceil($width / $ratio);
/* read binary data from image file */
$imgString = file_get_contents($file);
/* create image from string */
$image = imagecreatefromstring($imgString);
$tmp = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp, $image,
0, 0,
$x, 0,
$width, $height,
$w, $h);
imagejpeg($tmp, $file, 100);
return $file;
/* cleanup memory */
imagedestroy($image);
imagedestroy($tmp);
}
you can call the function like this :
resize_image($_FILE["fileToUpload"]["tmp_name"], 500, 500);
See more info here

Willyanto Halim
- 413
- 1
- 6
- 19
-
Note also that the code after the return statement will never be executed. – David Newcomb Dec 10 '16 at 01:50