2

This is a bit of an odd one. Users can upload an image to the server, insert some text and then from server side I create a new image with the user's text and the uploaded image.

To create to new image I am using imagecreatefrompng or jpg depending on the filetype of the uploaded file.

If the user does not like the created image, the user can edit the text or upload another image and hit submit again.

Create image from user's uploaded image and test

This all works as it should except for one occurrence. When the user uploads a png file the new image is created BUT if the user decides to change some text and have the same png file I get this warning:

Warning: imagecreatefrompng(): '..path.../temp/1404381132_my_png.png' is not a valid PNG file in ...path\save_image.php

Which is a bit weird really, if the same image worked the first time why doesn't it work the second time?

I've tested the same thing on jpgs and there were no problems.

Just to give you an idea of some test cases:

Test Case 1

User text 1: abc User text 2: abc Image: img.jpg

Image is created, No Errors occur

User decides to change some text but have the same image:

User text 1: abcdef User text 2: abcdef

Image is created, No Errors occur

User decides to change the image

Image: img_2.jpg or img_2.png

Image is created, No Errors occur

Test Case 2

User text 1: abc User text 2: abc Image: img.png

Image is created, No Errors occur

User decides to change some text but have the same image:

User text 1: abcdef User text 2: abcdef

Warning image is not a valid PNG Error

Test Case 3

User text 1: abc User text 2: abc Image: img.png

Image is created, No Errors occur

User decides to change the image:

Image: img_2.jpg or img_2.png

Image is created, No Errors occur

I guess this a bit too specific, not sure if anyone can solve this one.

j.grima
  • 1,831
  • 3
  • 23
  • 45

1 Answers1

0

This may be because of transparency and the way you're working with the PNG. I have had this a few times where working with PNG's causes issues. The way I have always resolved it is by creating another PNG from the upload and working on THAT file, not the uploaded one:

$uploaded = imagecreatefrompng('uploaded.png');

// Create a template canvas
$template = imagecreatetruecolor(imagesx($uploaded), imagesy($uploaded));

// Copy the uploaded image onto the canvas, keeping same height and width
imagecopyresampled($template, $uploaded, 0, 0, 0, 0, imagesx($uploaded), imagesy($uploaded), imagesx($uploaded), imagesy($uploaded));

// Save it and work on this one
imagepng($template, 'workingfile.png');

imagedestroy($template);
beingalex
  • 2,416
  • 4
  • 32
  • 71