0

I use the below code to resize images (jpg, png, gif). The code is working perfectly. But the problem is after resizing the images, all transparent images (both png and gif) have a black background.

How can I maintain the transparency so that resized images will have not have black background?

 $target = 'uploads/'.$newname;

 move_uploaded_file( $_FILES['file']['tmp_name'], $target);;

 $filename=$newname;
 if($ext=='jpg'||$ext=='jpeg') {
        $im = imagecreatefromjpeg('uploads/'.$filename);
    } else if ($ext=='gif') {
        $im = imagecreatefromgif('uploads/'.$filename);
    } else if ($ext=='png') {
        $im = imagecreatefrompng('uploads/'.$filename);
    }
    $ox = imagesx($im);
    $oy = imagesy($im);
    $nm = imagecreatetruecolor(400, 300);
    imagecopyresized($nm, $im, 0,0,0,0,400,300,$ox,$oy);
     imagejpeg($nm,  'thumbnails/' . $filename);
nickhar
  • 19,981
  • 12
  • 60
  • 73
Gijo Varghese
  • 11,264
  • 22
  • 73
  • 122
  • Related post: http://stackoverflow.com/questions/5688954/how-to-replace-black-background-with-white-when-resizing-converting-png-images-w?rq=1 – nickhar Mar 15 '14 at 01:12

2 Answers2

1

imagesavealpha() sets the flag to attempt to save full alpha channel information (as opposed to single-color transparency) when saving PNG images.

You have to unset alphablending (imagealphablending($im, false)), to use it.

Try adding

imagealphablending( $nm, FALSE );
imagesavealpha( $nm, TRUE );

Here:

.
.
$nm = imagecreatetruecolor(400, 300);
imagealphablending( $nm, FALSE );
imagesavealpha( $nm, TRUE );
.
.

Also consider using imagecopyresampled instead of imagecopyresized.

imagecopyresampled() smoothly interpolates pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity.

Use imagecopyresampled($nm, $im, 0,0,0,0,400,300,$ox,$oy);

Instead of imagecopyresized($nm, $im, 0,0,0,0,400,300,$ox,$oy);

tchow002
  • 1,068
  • 6
  • 8
  • Sorry it worked for png images. But not working for gif. Though it worked for png, images obtained are off poor clarity... colors are spread like that. Cannot be used. Instead of transparency is there any way to give white background?? – Gijo Varghese Mar 15 '14 at 01:43
  • try using `imagecopyresampled` instead of `imagecopyresized` – tchow002 Mar 15 '14 at 01:45
1

I also had similar troubles where a black background still appeared when using:

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

I found the below combination to be successful though:

imagecolortransparent($image, imagecolorallocate($thumbnail, 0, 0, 0));
imagealphablending($image, false);
thats4shaw
  • 104
  • 2
  • 8