Prithviraj Mitra
Prithviraj Mitra

Reputation: 11852

Resizing image with exact width and height in php

I am sure this topic has been discussed number of times and I have started doing this from yesterday evening but till now no complete satisfaction.I am using the following code and it gives me a resized image but the scaling is not correct.The height and width is not in it's correct proportion.

I couldn't find any good fiddle like jsfiddle where you can see the output so pasting my code here.

You can see the original image url here also I have attached a resized image.

http://distilleryimage4.s3.amazonaws.com/b1da08e4484511e38e4d0a7011810191_7.jpg

$filename = 'http://distilleryimage4.s3.amazonaws.com/b1da08e4484511e38e4d0a7011810191_7.jpg';
//the resize will be a percent of the original size
$percent = 0.589;
$percent_height = 0.294;

// Content type
header('Content-Type: image/jpeg');

// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent_height;

// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);

// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);


imagejpeg($thumb);
imagedestroy($thumb);

Resized Image

Upvotes: 0

Views: 1409

Answers (2)

aleation
aleation

Reputation: 4834

This is basically a Math problem:

You are scaling width and height to both different proportions ($percent and $percent_height). You should scale both of them (width and height) by the same percent, to get an image resized to the same ratio. Maybe I didn't understand your question but I think you should change this line:

$newheight = $height * $percent_height;

to

$newheight = $height * $percent;

(and remove $percent_height = 0.294; if we are not gonna use it here)

Upvotes: 2

Makla
Makla

Reputation: 10469

I would use Imagick. I was doing resizing with imagecreatetruecolor, but it takes a lot of time (0,5 seconds) to resize 1920*1080 image to 150*120.

If you still want to use imagecreatetruecolor: to get the correct scalling use this code.

Upvotes: 0

Related Questions