i want to resize uploaded images to width: 180px with proportional height. Is there any classes to do this?
Thanks for help!
I think this question can use an answer with an actual code example. The code below shows you how you to resize an image inside a directory uploaded
, and save the resized image in the folder resized
.
<?php
// the file
$filename = 'uploaded/my_image.jpg';
// the desired width of the image
$width = 180;
// content type
header('Content-Type: image/jpeg');
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
$height = $width/$ratio_orig;
// resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// output
imagejpeg($image_p, 'resized/my_image.jpg', 80);
?>
First you need to get the current image dimensions:
$width = imagesx($image);
$height = imagesy($image);
Then calculate the scaling factor:
$scalingFactor = $newImageWidth / $width;
When having the scaling factor just calculate the new height of the image:
$newImageHeight = $height * $scalingFactor;
Then just create the new image;
$newImage = imagecreatetruecolor($newImageWidth, $newImageHeight);
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newImageWidth, $newImageHeight, $width, $height);
Probably these snippets will help:
http://www.codeslices.net/snippets/resize-scale-image-proportionally-to-given-width-in-php http://www.codeslices.net/snippets/resize-scale-image-proportionally-in-php
at least they worked for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With