Bird87 ZA
Bird87 ZA

Reputation: 2160

Image resampling script for png and gifs

I have this PHP script that receives an uploaded image. The uploaded image is saved in a temp folder, and then this script resamples the image and saves it to the correct folder. A user can upload either JPG, PNG or GIF files. This script only caters for JPG files though.

How would I modify this script to resize both PNG's and GIF's without losing transparency?

$targ_w = $targ_h = 150;
$jpeg_quality = 90;

$src = $_POST['n'];
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );

$new_src = str_replace('/temp','',$_POST['n']);

imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);

imagejpeg($dst_r,$new_src,$jpeg_quality);

Upvotes: 0

Views: 636

Answers (2)

Mihai Iorga
Mihai Iorga

Reputation: 39724

JPEG images can't have transparent background.

Instead you can make the image based on imagesavealpha():

$targ_w = $targ_h = 150;
$newImage = imagecreatetruecolor($targ_w, $targ_h);
imagealphablending($newImage, false);
imagesavealpha($newImage, true);
$transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
imagefilledrectangle($newImage, 0, 0, $targ_w, $targ_h, $transparent);

$src = $_POST['n'];
$img_r = imagecreatefromstring(file_get_contents($src));
$img_r_size = getimagesize($src);

$width_r = $img_r_size[0];
$height_r = $img_r_size[1];
if($width_r > $height_r){
    $width_ratio = $targ_w / $width_r;
    $new_width   = $targ_w;
    $new_height  = $height_r * $width_ratio;
} else {
    $height_ratio = $targ_h / $height_r;
    $new_width    = $width_r * $height_ratio;
    $new_height   = $targ_h;
}

imagecopyresampled($newImage, $img_r, 0, 0, 0, 0, $new_width, $new_height, $width_r, $height_r);

$new_src = str_replace('/temp','',$_POST['n']);
imagepng($newImage, $new_src);

It will make a PNG from both PNG and GIF (that have transparent background, and resize to 150x150.

This is just an example, as it does not constrain proportions.

Upvotes: 1

Develoger
Develoger

Reputation: 3998

I had this problem few months ago and solved it by using code below:

imagealphablending($target_image, false);
imagesavealpha($target_image, true);

Upvotes: 0

Related Questions