Reputation: 10743
I am trying to resize images using cropThumbnailImage
. I use cropThumbnailImage
as it resizes to the shorter length of the original image and crops the image on the longer side equally on both sides so that center portion of the image remains uncropped. This works fine for jpg images but for png images, the resized pngs get a black background.
Following is the code I use.
$image = new \Imagick($src);
// resize & crop
$image->cropThumbnailImage($width, $height);
// save new resized file
$image->writeImage($dest);
Run this code for the following png image.
http://tuxpaint.org/stamps/stamps/animals/birds/cartoon/tux.png http://www.cs.csubak.edu/~mcabrera/CS211/transparent.png http://www.tcarms.com/media/assets/productPhotos/006_G2%20Contender/png/Pistol_12in_Ribbed_Blued_2720.png
The output image is resized as required but the png image gets black background.
Tried adding below lines from herebut did not work.
imagealphablending( $image, false );
imagesavealpha( $image, true );
There are other solutions out there in the web which achieve resizing of png images, but I did not find a solution that resizes image the way cropThumbnailImage
does.
Upvotes: 3
Views: 3232
Reputation: 4438
Transparency is preserved using the following snippet:
$im = new Imagick($imgPath);
$im->setImageFormat('png');
$im->writeImage('/files/thumbnails/new_title.png');
Upvotes: 2
Reputation: 11271
There is not transparency in your JPG... The JPG is not a transparent image... PNG and GIF are necessary here.
If you are refering to PNG, there is a PHP code who will help you to resize PNGs with transparency:
$x = "COORDINATES - X for crop";
$y = "COORDINATES - y for crop";
$w = "width";
$h = "height";
$img = imagecreatefrompng($img_path);
imagealphablending($img, true);
$img_cropped = imagecreatetruecolor($w, $h);
imagesavealpha($img_cropped, true);
imagealphablending($img_cropped, false);
$transparent = imagecolorallocatealpha($img_cropped, 0, 0, 0, 127);
imagefill($img_cropped, 0, 0, $transparent);
imagecopyresampled($img_cropped, $img, 0, 0, $x, $y, $w, $h, $w, $h); // you can also use imagecopy() here
imagepng($img_cropped, "your_image_cropped.png", 2);
imagedestroy($img);
imagedestroy($img_cropped);
EDIT: Try this:
$image = imagecreatefrompng ( $filename );
$new_image = imagecreatetruecolor ( $width, $height ); // new wigth and height
imagealphablending($new_image , false);
imagesavealpha($new_image , true);
imagecopyresampled ( $new_image, $image, 0, 0, 0, 0, $width, $height, imagesx ( $image ), imagesy ( $image ) );
$image = $new_image;
// saving
imagealphablending($image , false);
imagesavealpha($image , true);
imagepng ( $image, $filename );
Don't forget to define $filename, $width, $height!!!!
Upvotes: 0