REST API Image Compressor PHP

·

2 min read

Table of contents

No heading

No headings in the article.

php-image-compress.jpg

Hi Developpers, today we gonna build an image compressor client for users to use it compressing and editing their images

We will need the following:

so as our project will be user friendly we will read image from link, for that we will use CURL ( I tried all other ways and find out that CURL has the fastest response time for images) :

    $c = curl_init();
    curl_setopt_array($c, [
        CURLOPT_URL => $IMAGE_URL,
        CURLOPT_RETURNTRANSFER => true,
    ]);
    $data = curl_exec($c);
    curl_close($c);

a compress proccess and coverting to webp (the most compressed format) :

    if ($data) {
        $image = imagecreatefromstring($data);
        ob_start('ob_gzhandler');
        imagewebp($image, null, 50);
        echo ob_get_clean();
    } else
        echo file_get_contents("placeholder.png");

Now for the style and editing proccess we will need to require the "GD ImageStyle" library, and then add the following code just after creating the image:

        $image =  imagestyle($image, $STYLE);

the last thing is to define header (webp) and activate Zlib compressing library:

header('Content-Type: image/webp');
ini_set('zlib.output_compression', 1);
ini_set('zlib.output_compression_level', 9);

the finale code after replacing $IMAGE_URL with $_GET['url'] and $STYLE with $_GET['style'] to make it easier for client to use it:

<?php
header('Content-Type: image/webp');
ini_set('zlib.output_compression', 1);
ini_set('zlib.output_compression_level', 9);

require_once('gd_imagestyle.php');

if (isset($_GET['url'])) {
    $c = curl_init();
    curl_setopt_array($c, [
        CURLOPT_URL => $_GET['url'],
        CURLOPT_RETURNTRANSFER => true,
    ]);
    $data = curl_exec($c);
    curl_close($c);
    if ($data) {
        $image = imagecreatefromstring($data);
        $image =  imagestyle($image, $_GET['style'] ?: 'background:255.0.0');
        ob_start('ob_gzhandler');
        imagewebp($image, null, 50);
        echo ob_get_clean();
    } else
        echo file_get_contents("placeholder.png");
} else
    echo file_get_contents("placeholder.png");

Here is a Live Preview

I hope you find my code usefull, any question i'm here! Have a geat CODE ;)