1

I am simply trying to return an PNG image through PHP, but I have a problem with the transparency not showing right. (Basically one PHP file will be capable of returning any of my images.)

I use simple code to return the image:

<?php
    $im = imagecreatefrompng("images/fakehairsalon.png");
    header('Content-Type: image/png');
    imagepng($im);
    imagedestroy($im);
?>

The original image looks like this: Original image

And the one returned via PHP (and that piece of code) looks like this: Messed up image

Is there anything I can do to prevent this and make the image come through normal?

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
Pangolin
  • 7,284
  • 8
  • 53
  • 67
  • There has been a similar question with answer right here: [http://stackoverflow.com/questions/1705098/php-imagepng-and-transparency][1] [1]: http://stackoverflow.com/questions/1705098/php-imagepng-and-transparency – bjornruysen Sep 09 '11 at 12:28
  • I know, read through all these, but they seem to 'save' the images etc... I only want to return (pass it along) to the browser – Pangolin Sep 09 '11 at 12:30
  • @Alvaro, I am not trying to manipulate the image, only to pass it along to the browser – Pangolin Sep 09 '11 at 12:32
  • true, my bad.. Temporarly saving it and returning that one might be a workaround? – bjornruysen Sep 09 '11 at 12:32
  • @bjorn then there's no need to throw it through php! – Dunhamzzz Sep 09 '11 at 12:34
  • @Nideo: don't use image manipulation functions then. Pick your favourite [file system function](http://es.php.net/manual/en/ref.filesystem.php) instead, such as [readfile()](http://es.php.net/manual/en/function.readfile.php). – Álvaro González Sep 09 '11 at 12:35
  • @Alvaro & Dunhamzzz , The purpose is a bit more complex than that snippet of code, there will be calculations etc to determine which image to display, and then the relevant image will be passed back. But anyhow, it works fine now with Alvaro's answer below. thanks – Pangolin Sep 09 '11 at 12:40

1 Answers1

1

As explained in a user comment, you must do this:

<?php
$im = imagecreatefrompng("borrame.png");
header('Content-Type: image/png');

imagealphablending($im, true); // setting alpha blending on
imagesavealpha($im, true); // save alphablending setting (important)

imagepng($im);
imagedestroy($im);
?>

Update: This answer was assuming that your code is an except from a bigger script you are using to do on-the-fly image manipulation.

If you don't want to change the original file, this is a plain waste of memory and CPU cycles. You can use file system functions to read it as a regular file, such as readfile().

It's also worth noting that using PHP to deliver a file only makes sense if you want to do something else as well, such as:

  • Restricting access to the file
  • Keeping a counter
Álvaro González
  • 142,137
  • 41
  • 261
  • 360