This article demonstrate a PHP script which can be used to resize PNG image with transparent background. With the script given below we can pass custom width and size for resized image. The script is given below:
<?php
$original_img = 'file_path';// uploads/user_21098764.png
$new_img = 'path to save file';//uploads/thumb_user_21098764.png
$width = 300;//width for new image
$heigth = 200;//height for new image
resize($width, $height, $new_img, $original_img);
/*
* Function creates a new image from original image with defined resolution
*/
function resize($width = NULL, $height = NULL, $targetFile, $originalFile) {
$img = imagecreatefrompng($originalFile);
/*if custom values for width and height are not set,
*Calculate from image original width and height
*/
if($width != NULL && $height != NULL){
$newWidth = $width;
$newHeight = $height;
}else{
$imgWidth = imagesx($img);//get width of original image
$imgHeight = imagesy($img);
$newWidth = intval($imgWidth / 4);
$newHeight = intval($imgHeight /4);
}
$newImage = imagecreatetruecolor($newWidth, $newHeight);
imagealphablending($newImage, false);
imagesavealpha($newImage,true);
$transparency = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
imagefilledrectangle($newImage, 0, 0, $newHeight, $newHeight, $transparency);
imagecopyresampled($newImage, $img, 0, 0, 0, 0, $newWidth, $newHeight, $imgWidth, $imgHeight);
imagepng($newImage,$targetFile);
}
?>
Note : The above script is using functions of GD library, So please first check your server configuration that GD library is installed or not.
0 Comment(s)