Wednesday, August 17, 2011

Preserve PNG Transparency when resizing image in PHP


For Image manipulation PHP offers variety of functions. When working the Image processing in live projects, thumbnail of fly. Image Resize is often used by us.  Working thumbnails and resize process. The Image Format such JPEG is not a problem but working with PNG, GIF Images with Transparency it creates a block overlay on alpha channel. Here is my solution to resolve this Issue of Alpha fixes.


<?php
header('Content-Type: image/png');
// Set New widht and height of the Image
$newwidth=200;
$newheight=200;

// Create place holder for new size
$new_image = imagecreatetruecolor($newwidth, $newheight);
// Apply aplha bleding and alpha save
imagealphablending($new_image, false);
imagesavealpha($new_image, true);  

// Load Original PNG Image
$source = imagecreatefrompng("sample.png");
// Apply Alpha Blending
imagealphablending($source, true);
// Copy Source image to New Image
imagecopyresampled($new_image, $source, 0, 0, 0, 0, $newwidth, $newheight, imagesx($source), imagesy($source));
// Out put the new resized image with Transparency.
imagepng($new_image);
?>


No comments:

Post a Comment