The PNG Mime Type

About using the PNG mime type to deliver images to clients from the server side.

4007 views
d

By. Jacob

Edited: 2020-07-04 12:35

PNG Mime Type.

The content-type used to deliver PNG files on the internet is image/png, and the standard file extension is .png.

PNG files are mostly useful for screenshots and small graphical elements on a page, since it is in this context they achieve an optimal compression level. For photos, JPG is typically a better format; however, WebP generally accomplish the lowest file-sizes while retaining same quality.

The compression level accomplished with PNG files will depend on various factors.

See also: The Difference Between PNG8, PNG24, and PNG32

A HTTP response that delivers a PNG file may look like this:

HTTP/1.1 200 OK
content-type: image/png
content-length: 11772

To deliver a PNG image content-type with PHP:

$image_data = file_get_contents('some-inage-file.png');
header('content-type: image/png');
echo $image_data;
exit();

Creating PNG images from PHP

PNG images may be created from PHP using the GD Library, but you may need to install it manually before you are able to use it.

Note. See this article to learn how to install the GD Library for your system: Installing and Using GD Library with PHP

After making sure the GD Library is installed, you will be able to create and manipulate PNG files from PHP.

How to compress PNG images

Saving an image as .png with your favorite image editor is not always going to yield the best compression, and while there is a lot of commercial software that offers to optimize PNG files, it is probably better to stick with open source solutions.

I have personally found that free open source programs has been able to provide better compression than non-free competitors. It has been some time since I tested it now, so I can not say if this is still the case.

You should avoid online compressors, as they can embed tracking code into your images. Of course, the code will just be idling around without causing much harm; but the site creating it will be able to tell that your image was created using their service.

For Windows, you can use PNGGauntlet, and on Linux you can use Trimage:

  1. https://pnggauntlet.com/ - PNGGauntlet
  2. https://trimage.org/ - Trimage

Tell us what you think:

  1. In this Tutorial, it is shown how to redirect all HTTP requests to a index.php file using htaccess or Apache configuration files.
  2. How to create a router in PHP to handle different request types, paths, and request parameters.
  3. Tutorial on how to use proxy servers with cURL and PHP
  4. When using file_get_contents to perform HTTP requests, the server response headers is stored in a reserved variable after each successful request; we can iterate over this when we need to access individual response headers.
  5. How to effectively use variables within strings to insert bits of data where needed.

More in: PHP Tutorials