1

There is something very weird happening with my imagecopymerge function in PHP. I am trying to merge these two png files one on top of the other and the position where these will be merged is obtained dynamically from a drag-able canvas in an html page. Through a post form, I'm submitting the 'x' and 'y' coordinates where I want the merge on the destination image to happen ($dst_x and $dst_y parameters according to the PHP Man.) to my php file.

When I try to dynamically set these two parameters in the actual calling of the function, the resulting image is dumped correctly into the browser but when I try to right-click Save As... , on the saved image, the source (merged) image ($src_img) starts on the (0,0) coords., and not on the ones I specified (or rather, the user). If I try to save it as I would a whole webpage (Ctrl+S or File... Save) it is saved correctly (i.e. the $src_image starts on the specified x and y coordinates).

However, if I hard-code some x and y coordinates, this does not happen and I am able to save it through every method (drag-and-drop to Desktop, File... Save... etc.) in the browser and it's saved correctly and consistently.

This is my code:

<?php 
if(isset($_POST)){

    // Create image instances
    $src  = imagecreatefrompng('hello.png');
    $dest = imagecreatefrompng('./img/image2.png');
    imagealphablending($dest, true);
    imagesavealpha($dest, true);

    // Copy and merge
    $posX = (int)(isset($_POST['x']) ? $_POST['x'] : null);
    $posY = (int)(isset($_POST['y']) ? $_POST['y'] : null);

    imagecopymerge($dest, $src, $posX, $posY, 0, 0, 200, 200, 100);  //dynamic setting

    header("Content-Disposition: inline; filename=\"rendered.png\"");
    header('Content-Type: image/png');

    // Output and free from memory

    imagepng($dest);
    imagedestroy($src);
    imagedestroy($dest);
}
?>

I'm not sure why Firefox is doing this but I appreciate any help.

jake2389
  • 1,166
  • 8
  • 22

1 Answers1

1

If anyone's having the same issue, I solved this by changing the submit method on the HTML form. Instead of post, I used get and it worked. Not sure why it did, or why it would make anything of a difference in the actual values, but hey, it worked.

UPDATE:

Figured what was really causing the problem. From the PHP.net in the imagepng() function man:

If you're generating an image dynamically based on post data and don't want to save it to the server, sending it to be displayed can cause problems as when the person tries to save it, the browser will request it again from the server (causing any post data to be lost and probably a corrupted png).

The easiest way to get around this is to force it to download using the content disposition header, for example:

<?php
    header('Content-Disposition: Attachment;filename=image.png');
    header('Content-type: image/png');
?>
jake2389
  • 1,166
  • 8
  • 22