Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proportional image resizing

Tags:

php

image

resize

i want to resize uploaded images to width: 180px with proportional height. Is there any classes to do this?

Thanks for help!

like image 417
Mirgorod Avatar asked Jun 22 '11 12:06

Mirgorod


2 Answers

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);
?>
like image 184
ndequeker Avatar answered Sep 22 '22 22:09

ndequeker


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.

like image 27
Michael Hoffmann Avatar answered Sep 23 '22 22:09

Michael Hoffmann