-2

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

swaroop
  • 19
  • 1
  • 3

1 Answers1

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