I am attempting to create thumbnails of photos using PHP's GD library.
Here are the steps I am taking.
Here is my code:
private function getExtension($filename) {
$position=strrpos($filename, '.');
$extension = strtolower(substr($filename, $position+1));
if ($extension == "jpg") {
$extension = "jpeg";
}
return $extension;
}
public function saveImage($parameters) {
$extension=$this->getExtension($parameters['filename']);
$createImageFunc="imagecreatefrom".$extension;
$imgResource=$createImageFunc(SITE_PATH."tmp/{$parameters['filename']}");
$width=imagesx($imgResource);
$height=imagesy($imgResource);
$ratio=$height/$width;
$thumbnail=imagecreatetruecolor(100, 100*$ratio);
imagecopyresized($thumbnail, $imgResource, 0, 0, 0, 0, 100*$ratio, 100, $width, $height);
$imgResult=imagejpeg($imgResource, SITE_PATH."images/{$parameters['galleryName']}/{$parameters['filename']}");
$thumbResult=imagejpeg($thumbnail, SITE_PATH."images/{$parameters['galleryName']}/thumbnails/{$parameters['filename']}");
}
The images are saving, but the copy is not working, there is empty black space in the thumbnail picture.
This is the original Image:
This is the image saved again with gd:
This is the thumbnail:
I've like quadruple checked imagecopyresize and from what I understand of it all the values in the code should be correct.
Here is what php.net has for the values:
bool imagecopyresized ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
Any one got any ideas?
Take a look at this: PHP/GD Imagestyle
You can easily create thumbnails or everything you want
// create a thumbnail
$thumb = imagestyle($image,'autosize:100 100');
// resize the image # resize:200 0; means width=200 height=auto
$resized = imagestyle($image,'resize:200 0;');
// crop it # left=0, top=50, width=200, height=200
$cropped = imagestyle($image,'crop:0 50 200 200;');
// and more
Working with PHP/GD can be tedious, so I wrote a library to make things much easier: SimpleImage
With SimpleImage, you can create a thumbnail in two simple lines:
// Load image from image.jpg
$image = new \claviska\SimpleImage('image.jpg');
// Create a 100x100 thumbnail, convert to PNG, and save to thumb.png
$image->thumbnail(100, 100)->toFile('thumb.png', 'image/png');
If you're still bent on doing it manually, check your imagecopyresized
parameters. Why is the width being multiplied by $ratio
?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.