API examples

Since COD was developed with the background in mind that each image is different and therefore needs to be checked individually to get the best possible result, the API is a little different. You'll send your image to the API and get a session ID back, with which you can then call the page "compress-or-die.com" in your browser with your image presented in the well-known GUI.

Here are some examples how to integrate COD into your scripts.

PHP

If you are a PHP developer the following CLI script could be useful. Use it like this:

$ php compress-or-die.com.php your-image.png

PHP has to be in your OS environment variable PATH and you need to have the CURL extension installed.
Works on Windows and MacOSX.

compress-or-die.php
<?php

define('FOR_VERSION', 2);

// set the host (use for debugging)
$host = 'http://compress-or-die.com';

// get filename passed to the script
$filename = $argv[count($argv) - 1];

// send file to the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host . '/api-v2');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
	// this is the filename that is offered to you on download
	'X-DOCUMENT-NAME: ' . basename($filename)
]); 
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));
$body = curl_exec($ch);
curl_close ($ch);

// parse the answer to get the session id
$answer = [];
foreach(explode("\n", trim($body)) as $line) {
	$parts = explode(':', $line, 2);
	$answer[$parts[0]] = $parts[1];
}

// check version
if ($answer['_VERSION'] != FOR_VERSION) {
	fwrite(STDERR, 'Aborting: This script is for version ' . FOR_VERSION . ', but the current version is ' . $answer['_VERSION'] . '.');
	exit(1);
}

// open the browser to show the image on compress-or-die.com
$command = stripos(getenv('OS'), 'Windows') !== false ? 'start' /* Windows */ : 'open'  /* Mac */;
shell_exec($command . ' ' . $host . '/' . $answer['_URL'] . '?session=' . $answer['_SESSION']);

Javascript

If you are a Javascript developer the following example script could be useful. Just copy the example to a file "index.htm" and open it in the browser.

index.htm
<!DOCTYPE html>
<html>
<head><title>JS Demo</title></head>
<body>
    
<input type="file" name="file" id="file" />

<script>
document.querySelector('#file').addEventListener('change', (e) => {
    const files = e.target.files
    if (files.length) {
        processFile(files[0])
    }
})

function processFile(file) {
    const FOR_VERSION = 2
    
    // get filename passed to the script
    var filename = file.name
    
    // send file to the API
    fetch('https://compress-or-die.com/api-v2', {
        method: 'POST',
        headers: {
            // this is the filename that is offered to you on download
            'X-DOCUMENT-NAME': filename,
        },    
        body: file    
    })
    .then(response => response.text())
    .then(response => {
        // parse the answer to get the session id
        const answer = {}
        response.split("\n").forEach(el => {
            let [key, ...value] = el.split(':');
            value = value.join(':');
            answer[key] = value
        })

        // check version
        if (answer._VERSION != FOR_VERSION) {
            throw new Error(`Aborting: This script is for version ${FOR_VERSION}, but the current version is ${answer._VERSION}.`)
        } else {
            // open the browser to show the image on compress-or-die.com
            location.href = `${answer._URL}?session=${answer._SESSION}`
        }
    })
}
</script>

</body>
</html>

Node.js

If you are a Node.js developer the following CLI script could be useful. Use it like this:

$ node compress-or-die.com.js your-image.png

First you have to install some node modules:

$ npm install request opn

Works on Windows, MacOSX and Linux.

compress-or-die.js
var request	= require('request');
var fs		= require('fs');
var path	= require('path');
var opn		= require('opn');

const FOR_VERSION = 2;

// get filename passed to the script
var filename = process.argv[process.argv.length - 1];

// send file to the API
request.post({
	url: 'http://compress-or-die.com/api-v2',	
	headers: {
		// this is the filename that is offered to you on download
		'X-DOCUMENT-NAME' : path.basename(filename)
	},
	body: fs.createReadStream(filename)
}, function(error, response, body){
	// parse the answer to get the session id
	var answer = {};
	body.split("\n").forEach(el => {
		let [key, ...value] = el.split(':');
		value = value.join(':');
		answer[key] = value
	});
	
	// check version
	if (answer._VERSION != FOR_VERSION) {
		process.stderr.write('Aborting: This script is for version ' + FOR_VERSION + ', but the current version is ' + answer._VERSION + '.');
		process.exit(1);
	}

	// open the browser to show the image on compress-or-die.com
	opn(answer._URL + '?session=' + answer._SESSION);
});

Python

If you are a Python developer the following CLI script could be useful. Use it like this:

$ py compress-or-die.com.py your-image.png

First you have to install a module:

$ pip install requests

Works on Windows and MacOSX.

compress-or-die.py
import sys, os, requests
from sys import platform
from subprocess import call

FOR_VERSION = 2

# get filename passed to the script
filename = sys.argv[-1];

# send file to the API
with open(filename, 'rb') as f:
	response = requests.post('http://compress-or-die.com/api-v2', data=f, headers={'X-DOCUMENT-NAME': os.path.basename(filename)})

# parse the answer to get the session id
lines = response.text.splitlines()
answer = {}
for line in lines:
	parts = line.split(':', 1);
	answer[parts[0]] = parts[1]

# check version
if (int(answer['_VERSION']) != FOR_VERSION):
	print('Aborting: This script is for version ' + str(FOR_VERSION) + ', but the current version is ' + answer['_VERSION'] + '.', file=sys.stderr)
	exit(1)


# open the browser to show the image on compress-or-die.com
from sys import platform
if platform == "darwin":
	call(['open', answer['_URL'] + '?session=' + answer['_SESSION']])
elif platform == "win32":
	call(['cmd.exe', '/c', 'start', answer['_URL'] + '?session=' + answer['_SESSION']])


Feedback

Christoph Erdmann

Your opinion is so important for me! Don't hesitate to drop me a line. I will do my best to implement your feedback.

Give feedback

You don't like ads? Support Compress-Or-Die and become a patron who does not see ads. Your upload limit gets doubled too!

News
Christoph Erdmann
Image compression with AI
2023-06-25

Wow! Google researchers have now proposed a new method that combines a standard autoencoder with a diffusion process to recover and add fine details discarded by the autoencoder. Interesting to see the possibilities AI opens up when compressing images.

How Should We Store AI Images? Google Researchers Propose an Image Compression Method Using Score-based Generative Models - MarkTechPost
MarkTechPostA year ago, generating realistic images with AI was a dream. We were impressed by seeing generated faces that resemble real ones, despite the majority of outputs having three eyes, two noses, etc. However, things changed quite rapidly with the release of diffusion models. Nowadays, it is difficult to distinguish an AI-generated image from a […]

Check out our Reddit channel if you want to comment on the news.