Optimize images - Losslessly compress images in php

307 views Asked by At

Images are stored in a different server than the one i use. Is there a way to losslessly compress them using php and after compression show the images to my site without having to download the images to my server and store them? I do not have any access to the server that the images are stored. I can only download them to my server. Right now i just use the url of the picture to load the images to my site but GTmetrix is constantly mentioning about losslessly compress the images. Any thoughts?

1

There are 1 answers

0
Revvz On

You can use something like the kraken-php image API to achieve your goal, granted you have access to the files of the server. If you have composer installed and running, you may use that too, but again, you need access to the server somehow. If you decide to access the files you can install using their install page. You have the option to return the request immediately in a file or you can post it to a URL that can be accessed by the server. Your request may look something like:

{
    "auth": {
        "api_key": "your-api-key",
        "api_secret": "your-api-secret"
    },
    "url": "http://image-url.com/file.jpg",
    "wait": true
}

and your response may look something like:

{
    "success": true,
    "file_name": "file.jpg",
    "original_size": 324520,
    "kraked_size": 165358,
    "saved_bytes": 159162,
    "kraked_url": "http://dl.kraken.io/d1aacd2a2280c2ffc7b4906a09f78f46/file.jpg"
}

Your PHP code for setting up the response may look something like:

require_once("Kraken.php");

$kraken = new Kraken("your-api-key", "your-api-secret");

$params = array(
    "file" => "/path/to/image/file.jpg",
    "wait" => true,
    "webp" => true,
    "lossy" => false
);

$data = $kraken->upload($params);

You can handle the response like you would a normal JSON request, and you can query the image URL for the processed image. However, you will need to sign up for their API, which is not free. If you are looking for a free solution, with fewer features, you can check out pngquant. This is coincidently how services like Kraken work, but it will take longer to have a robust system setup. You will, again, need some form of access to the server. Otherwise, you can't really do anything about it.