Parameters

The path or an open stream resource (which is automatically being closed after this function returns) to save the file to. If not set or NULL, the raw image stream will be outputted directly.

Note:

NULL is invalid if the quality and
filters arguments are not used.

quality

Compression level: from 0 (no compression) to 9.

filters

Allows reducing the PNG file size. It is a bitmask field which may be
set to any combination of the PNG_FILTER_XXX
constants. PNG_NO_FILTER or
PNG_ALL_FILTERS may also be used to respectively
disable or activate all filters.

User Contributed Notes 33 notes

The name "quality" for the compression parameter is quite misleading, as png compression is always lossless. The trade off is between speed and filesize, it cannot affect quality.

Here's something I found at stackoverflow; I haven't checked it, but if it is correct it should definitely included in the documentation:

---from php source (gd.h):

/* 2.0.12: Compression level: 0-9 or -1, where 0 is NO COMPRESSION at all,* 1 is FASTEST but produces larger files, 9 provides the best* compression (smallest files) but takes a long time to compress, and* -1 selects the default compiled into the zlib library.*/Conclusion: Based on the Zlib manual (http://www.zlib.net/manual.html) the default compression level is set to 6.---

Regarding suggestions to rescale the 0-99 quality range of jpeg into the 0-9 range of png, note that for jpeg 99 is minimum compression (maximum quality) while for png 9 is maximum compression (quality doesn't change).

"Tip: As with anything that outputs its result directly to the browser, you can use the output-control functions (http://www.php.net/manual/en/ref.outcontrol.php) to capture the output of this function, and save it in a string (for example)."

Problem: main.php execution ends before createImage.php writing the text to image, thus the unset($_SESSION['text']) destroys the text and you end up with empty image.Solution: move call to unset() as last statement of createImage.php

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:

Trying to resize a png 256 colors image and save it in 256 colors with a correct color palette ? (if you'll save a 256 color image in truecolor palette the result image will have a big size).I spent some hours trying various function to get a good quality 256 color png image, but because of color palette the result image quality was awful.But thank to the comment of zmorris at zsculpt dot com from imagetruecolortopalette function page, i figured out how to get a properly image!

Be careful when using a variable for the file name.PHP behavior with $filename differs when switching to PHP5.4 : PHP5.3 will use $filename='' the same way as $filename=NULL (e.g. no warning)<?php$im = imagecreatetruecolor(10,10);imagepng($im,'',9); # Warning: imagepng(): Filename cannot be emptyimagepng($im,NULL,9); # works as expectedimagedestroy($im);?>

// Select ALL villages from the DB and order by ascending ID // (Fields are numbered from top left to bottom right) $query = 'SELECT x, y, aid FROM x_world ORDER BY id ASC'; $result = @mysql_query($query) OR die('Can not select villages from table x_world!');

// Check whether there any villages at all if (mysql_num_rows($result)) {

// Select first village $row = @mysql_fetch_assoc($result);

// These variables save the location on which we are currently drawing $x_pointer = 0; $y_pointer = 0;

// Outer loop for the Y-coordinates for($y=400; $y >= -400; $y--) {

// Inner loop for the X-coordinates for ($x=-400; $x <= 400; $x++) {

// Once we reached the coordinates matching the current record selected from the DB: if ($row['x'] == $x AND $row['y'] == $y) {

My webserver, running 5.14 didn't like the header that was generated using imagepng(). It works find on my local test server and on 4.x from another host.

The generated image displays in the browser (IE, firefox) but when saved to a file or inserted into an RTF file, the image was corrupted. As a test, when attempting to right-click to save as, the image format was not recognized.

The only work-around appears to be adding the additional paramaters.

So instead of just imagepng($image); //DIDNT WORK--CORUPT IMAGE

This workedimagepng($image,NULL,0,NULL);

and saving to disk, this worked:imagepng($image,$file_location,0,NULL);

I just lost about 4 hours on a really stupid problem. My images on the local server were somehow broken and therefore did not display in the browsers. After much looking around and testing, including re-installing apache on my computer a couple of times, I traced the problem to an included file. No the problem was not a whitespace, but the UTF BOM encoding character at the begining of one of my inluded files...So beware of your included files!Make sure they are not encoded in UTF or otherwise in UTF without BOM.Hope it save someone's time.

Having your pictures stored in a database sounds great but brings you a lot of trouble.Storing images in a DB you will have a script show.php that will appear in <img> tags: <img src='show.php?img_id=$some_id'>But if you want to have REGISTER GLOBALS = OFF, you are in trouble and there is no way (at leas as far as i know) to solve the problem but to put te img from the DB in a file and put the coresponding file name in the <img> tag. But this brings another problem: simultaneous accesses to the page. So you will have to find a way to give unique names to the picture files for each simultaneous access to the page. The solution might be using sessions. This is how you end up having a very compleh PHP script for a very simple problem. So, the basic ideea is " do not store your pictures in a blob unless you know exactly what you are doing".

I was curious about the relationship between quality, processing time and resulting image size, so I created this little benchmark to test it (The image used was originally RGB_24bits_palette_R85.png, found on wikipedia). Results are at the bottom.<?php$sizes = ['32', '64', '128', '256', '512', '1024', '2048'];

# selecting correct zoom factor, so that the image always keeps in the given format# no matter if it is more higher than wider or the other way aroundif((100-$_X) < (100-$_Y)) $_K = $_X;else $_K = $_Y;

PNG files are already compressed. They use a lossless compression algorithm. If you are using HighColour images, the compression only does so much. For low colour images (16 or 256) the compression is much better.

It is pointless trying to compress the images further before sending to a browser.

I have experienced segfaults and bus errors with the following configuration: FreeBSD4.4, Apache 1.3.26, PHP 4.2.2, GD-1.8.4, PDFlib 4.0.1. The apache process crashed when calling the imagepng function, but it didn't crash when calling the imagejpg function, or imagecreatefrompng...

So the problem was not with the png library, but rather with the PDFlib. Even though all the threads led to a png-problem... so I have simply upgraded to PDFlib 4.0.3 (w/o any special configure arguments; --with-libpng didn't work anyways), recompiled PHP, and now everything works (imagepng, pdf creation, etc.).

If you are outputting a PNG directly in response to a client request it is important to check your web server configuration.

Some clients may request your images with a <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">accept header</a> of image/*. Default configurations of Apache and possibly other servers will by default NOT allow your script to run in response to this request.

You could set up a 'img' directory in your webspace.In that directory there will be two files: a .htaccess file and a img.php filethe .htaccess file contains the following code:ErrorDocument 404 /img/img.php

if you use a url for your image like http://test.com/img/image1.jpeg, which doesn't exist, normally you would get a 404-page. in this case, the 404 is being handled by img.php, which brings up the required image...

If you care about speed, you probably already cache your generated images to a file. In that case, DON'T use "createimagefrompng" and "imagepng" to output the image. Use fpassthru instead. It is literally hundreds of times faster.

This is my way to store PNG-images in a MySQL database... You cannot directly store the PNG-image in a variable, and then parse it in the database, cos if you try to define it to a variable, it'll still just output it...In my method i use three functions to "capture" the output and store it in a variable; ob_start (to start the output buffering), ob_get_contents (to capture the output), and ob_end_clean (to erase the cache, and end the output buffering)

PNG images (as any image) can be stored in a MySQL blob field, but if you want to do this, you'll want to serialize the image stream into a better form. I would recommend base64_encode() and base64_decode(). (Just fopen() the file, fread() the contents in, base64_encode() the string, and fire off your SQL query (use addslashes()/stripslashes() to be more secure)).

This has been posted an innumerable amount of times throughout the site, but it's still terrible that a lot of users simply don't understand this and use it to its full potential.

I would also recommend that if you are doing images this way, to keep an image cache folder somewhere that PHP can access (possibly even somewhere off your webroot?). That way if your website is swamped with traffic it won't kill the SQL server.

When changeing the PHP version from 4 to 5 I found out, that PHP5 handles imagepng() more restrictive than in PHP4. I'd used

imagepng($image,'',90);

to reduce the image quality whithout saving the image as a file. The quality parameter is not supported at all, I used imagejpg before and simply changed the function to imagepng whithout taking care of the existing parameters. It did not matter and there was no error in PHP4. But in PHP5, the image will not be shown anymore. So you have to remove it to have the standard:

If you want to resize a png-24 image and preserve the alpha channel you need to set imagealphablending($im_dest, false) on the destination image just after creating it with imagecreatetruecolor() and do a imagesavealpha($im_dest, true) on it before saving it: