MacMac
MacMac

Reputation: 35301

On-the-fly thumbnails PHP

I came up with this:

<?php 

$dir = $_GET['dir'];

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

$create = imagecreatetruecolor(150, 150); 
$img = imagecreatefromjpeg($dir); 
imagecopyresampled($create, $img, 0, 0, 0, 0, 150, 150, 150, 150); 

imagejpeg($create, null, 100); 

?>

It works by accessing:

http://example.com/image.php?dir=thisistheimage.jpg

Which works fine... but the output is awful:

alt text

Can someone fix my code for the image to be 150 x 150 covering the black area...

Thanks.

SOLUTION:

<?php 

$dir = $_GET['dir'];

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

list($width, $height) = getimagesize($dir);

$create = imagecreatetruecolor(150, 150); 
$img = imagecreatefromjpeg($dir); 

$newwidth = 150;
$newheight = 150;

imagecopyresized($create, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

imagejpeg($create, null, 100); 

?>

Upvotes: 2

Views: 7511

Answers (3)

Luc
Luc

Reputation: 1528

As others suggested, last two parameters should be original size of the image.

If $dir is your filename, you can use getimagesize to obtain picture's original dimensions.

You can use imagecopyresized or imagecopyresampled. Difference is that imagecopyresized will copy and resize while imagecopyresampled will also resample your image which will yield better quality.

<?php 

$dir = $_GET['dir'];

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

$create = imagecreatetruecolor(150, 150); 
$img = imagecreatefromjpeg($dir);
list($width, $height) = getimagesize($dir);
imagecopyresampled($create, $img, 0, 0, 0, 0, 150, 150, $width, $height);

imagejpeg($create, null, 100); 

?>

Upvotes: 1

CharlesLeaf
CharlesLeaf

Reputation: 3201

The last 2 150 should be the original width and height of the full sized image.

Upvotes: 1

Yuval Adam
Yuval Adam

Reputation: 165182

Use imagecopyresized:

$newwidth = 150;
$newheight = 150;
imagecopyresized($create, $image, 0, 0, 0, 0, $newwidth, $newheight, $oldwidth, $oldheight);

Upvotes: 6

Related Questions