What your code does is more or less as follows:
// Load the PNG file from disk into memory
$im2 = imagecreatefrompng($image)
$im2
is now a resource
, referencing a image. Once in memory, it is not a png or a jpeg; it is a raw, uncompressed data. The "format" of an image specifies how that raw data is packaged and formatted; at this point, it has no such formatting. It's just data in memory.
// Some code which works with the image in memory, adding your watermark?
imagecopy() and more code here
// Tell the browser that we're output a JPG
header("Content-Type: image/jpeg");
If you request a jpg (ie http://host.com/image.jpg) then the server takes care of writing this header for you. If you're making a JPG on the fly via PHP you have to manually output the header. Otherwise, PHP assumes you're writing HTML and outputs the appropriate headers for you as soon as write anything to stdout, either via echo
or just by having text/whitespace outside of <?php ?>
tags.
// compress as a jpeg, and send to browser
imagejpeg($im2,'',50);
imagejpeg
takes the raw image, compresses it as a jpg, and writes it to either a file (if you give it a filename) or stdout (which sends it to the browser). Technically to output to the browser, the 2nd argument should be null
, not ''
. The final parameter, 50, specifies the jpeg quality as percentage. 100 is high-quality, 0 is low quality.