How to convert images on PHP without Imagick?

Alexey Fedorchak
2 min readMar 22, 2021

--

There is popular opinion that PHP can handle images only if Imagick extension is installed. Indeed sometimes it is better to install Imagick, because we can’t overestimate the possibilities which this library provides..

But installation additional packages usually takes some time and may create some issues especially if that is running project.

But do we really need to use Imagick all the time? Basically not!
PHP has a lot of native functions for processing images. Actually if your task is just to convert images, you absolutely don’t need to install Imagick.

Converting images on PHP can be easily done by passing these steps:
1) load image as a string into operating memory (let’s call it “buffer”);
2) save image into the buffer using some specific format (PNG, JPEG..);
3) get data from buffer and put them into file (save the image in necessary format into the file).

So, let’s see how these steps looks in the code!

The first step can be done like this:

$image = imagecreatefromstring(
file_get_contents('/path/to/images/image.jpg')
);

As you can see PHP has function imagecreatefromstring(), which can load image to buffer as a string. The only thing you need is to get image data as a string. In the given example I used for this another native function file_get_contents().

Next step is to convert image and put it to the buffer. Let’s say we need convert image to PNG, for this we may do like this:

ob_start();
imagepng($image);

$pngImageData = ob_get_contents();
ob_end_clean();

Based on this example, we see that image is loaded to buffer as a PNG image. For this we used function imagepng.

For JPEG/JPG you may use imagejpeg(), for TIFF you may use imagetiff(). See documentation here: https://www.php.net/manual/ru/function.imagepng.php

Functions ob_start(), ob_clean() are using for reserving and freeing memory in buffer. Using ob_get_contents() you may get content from the buffer.

Now, it seems we’ve missed one last step - save image to the file! Usually I do it like this:

file_put_contents('/path/to/images/image.png', $pngImageData);

Also you may save converted image directly from imagepng(). To get more details, please read docs on php.net.

Hope this article was useful, if you have some questions, please contact me via email: ofedorchak68@gmail.com.
or via Linkedin: shorturl.at/oEX05.

--

--

Alexey Fedorchak
Alexey Fedorchak

Written by Alexey Fedorchak

Hi! I’m expert certified Laravel/PHP developer.

No responses yet