0

I'm trying to build a script that will resize a png and save it to the server as an 8bit png, from a <input type='file' /> but I am having a few issues.

$srcimage = imagecreatefrompng($orig_source);
$img = imagecreatetruecolor($resize_width, $resize_height);
$bga = imagecolorallocatealpha($img, 0, 0, 0, 127);
imagecolortransparent($img, $bga);
imagefill($img, 0, 0, $bga);
imagecopy($img, $srcimage, 0, 0, 0, 0, $resize_width, $resize_height);
imagetruecolortopalette($img, false, 255);
imagesavealpha($img, true);
imagepng($img, $filepath);
imagedestroy($img);

How to convert PNG to 8-bit PNG using PHP GD library

This works great when i upload a 32bit png, and when i upload an already 8bit png, it keeps the transparency and resizes as expected, but when I choose to upload a 24bit png I get this error

Warning: imagecreatefrompng() [function.imagecreatefrompng]: '/share/MD0_DATA/Qweb/php2zRiNv' is not a valid PNG file

Warning: imagecopy() expects parameter 2 to be resource, boolean given

I understand the second error is because the imagecreatefrompng failed, but I don't understand why that should fail as it is a valid png file!

Any help would be greatly appreciated!

Community
  • 1
  • 1
rorypicko
  • 4,194
  • 3
  • 26
  • 43

1 Answers1

1

If you're saving it from an application such as Photoshop make sure you use the save for web option as some applications embed non-standard data such as guides.

Andy Gee
  • 3,149
  • 2
  • 29
  • 44
  • Wow, I hope this isn't the case!! I'll do some tests now and save a few png's out, with and without guides, at different bit depths. If this is the case is there anyway around it? – rorypicko Jul 23 '13 at 13:58
  • ImageMagick can handle it. You could convert all files with that on one go or use that instead of GD – Andy Gee Jul 23 '13 at 14:00
  • Hmm, I just tried that and both uploaded fine. Maybe the png I am trying to upload before is corrupt in another way... I'll try that ImageMagick now though, thanks for the suggestion. I'll mark this answer up and if ImageMagick works correct then accept the answer as the issue does seem to be corrupt PNG as you said! Thanks Andy – rorypicko Jul 23 '13 at 14:02