Home > Programming > Resizing an image file

Resizing an image file

I had to recently make a change in an image uploading website. If the image width is too wide, it looks crappy. So what I needed was to reduce the width to 800 if the width was greater than 800. Here is the code to do that ( Hope you can understand it yourself…

$file_name_for_resize= './uploads/'. $userfile_name;

$work = new ImgResizer($file_name_for_resize); //
$work -> resize(800,
$file_name_for_resize); // resized image has a max width of 800 pixels

echo "done";

class ImgResizer {
private $originalFile = '';
public function __construct($originalFile = '') {
$this -> originalFile = $originalFile;
}
public function resize($newWidth, $targetFile) {
if (empty($newWidth) || empty($targetFile)) {
return false;
}

$src = imagecreatefromjpeg($this -> originalFile);
list($width, $height) = getimagesize($this -> originalFile);

if ( $width < 800) // resize only if the width is greater than 800
{ $newHeight = $height;
$newWidth = $width;

}

$newHeight = ($height / $width) * $newWidth;

$tmp = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
if (file_exists($targetFile)) {
unlink($targetFile);
}
imagejpeg($tmp, $targetFile, 85); // 85 is my choice, make it between 0 – 100 for output image quality with 100 being the most luxurious
}
}

Programming ,

  1. No comments yet.
  1. No trackbacks yet.