Getting Started
To plug into the power and speed of Kraken API you need to create your Kraken Account (for free!) and obtain your unique Kraken API Key. You will find your API Key in your Account Settings. Once you have created (and activated) your account, you can start using Kraken API in your applications.
Limitations
Kraken API is in public beta stage. It means we are still testing this service with all our users. Right now you can optimize 50 images per day, up to 500 KB each. This type of account will always remain free. In the near future we will introduce paid plans with extended quotas and advanced optimization options.
How to use
You can optimize your images in two ways - by providing an URL of the image you want to optimize or by uploading an image file from your disk directly to Kraken API. The first option (image URL) is great for images that are already in production environment or any other place available on the Internet. The second one (image upload) is ideal for deployment process or build script where you don't have your images on the Internet yet.
Image URL
If you want to feed Kraken API with URLs to your images note that this type of communication is available only via JSON. It means that you have to send request to the API as JSON strings. You also have to set Content-Type header as application/json in your request. Kraken API will always return a JSON object in a response body.
Kraken API accepts HTTPS POST requests only. Please notice that we only offer API access through SSL secured HTTPS connections, which means you have to use HTTPS protocol in your requests. Every POST request body must include a well-formed JSON and consist of two sections: auth and image. In the auth section you need to provide your username and password to your Kraken Account and of course your Kraken API Key. image section must contain a valid URL to the image you want to optimize.
Stay calm - we use a JSON validator so if any property is missing or there's a typo, you will be notified. Here's an example of a valid JSON object:
{
"auth": {
"user": "your-kraken-user",
"pass": "your-kraken-pass",
"apikey": "your-kraken-api-key"
},
"image": {
"url": "http://awesome-website.com/images/header.png"
}
}Kraken API will return a JSON object. In the response body you will find original file size, optimized (kraked) file size, amount of savings and of course URL to download optimized image. Note the "success": true property:
{
"success": true,
"originalSize": 324520,
"krakedSize": 165358,
"savedBytes": 159162,
"savedPercent": "49.04%",
"krakedURL": "https://api.kraken.io/kraked/3574043e43e8e47858e5/header.png"
}If anything goes wrong you will find the "success": false property and error message in the response:
{
"success": false,
"error": "Couldn't get this image"
}Supported Protocols and HTTP/FTP Authentication
Kraken API supports HTTP, HTTPS and FTP protocols in image URL. In fact, it even supports images on password protected locations! If you use HTTP(S) or FTP authentication to access your images you can pass username and password (urlUser and urlPass properties) directly to your request in the image section.
If you need authentication to access your images, do not confuse your Kraken Username and Kraken Password with credentials you need to pass in order to access password protected locations. Here's an example of a POST request body with credentials needed to access protected location:
{
"auth": {
"user": "your-kraken-user",
"pass": "your-kraken-pass",
"apikey": "your-kraken-api-key"
},
"image": {
"url": "ftp://protected-ftp-server.com/images/header.png",
"urlUser": "your-ftp-user",
"urlPass": "your-ftp-pass"
}
}Image Upload
If you want to upload your images directly to Kraken API you dont't need to set any special headers in your request. Upload URL is: https://api.kraken.io/file. Kraken will treat your request as standard multipart/form-data. The only mandatory field (except the file itself) is auth field with credentials as JSON string:
{
"user": "your-kraken-user",
"pass": "your-kraken-pass",
"apikey": "your-kraken-apikey"
}Kraken API will return the same JSON object as for Image URL optimization type. In the response body you will find "success": true property, original file size, optimized (kraked) file size, amount of savings and of course URL to download optimized image. If anything goes wrong you will find the "success": false property and error message in the response.
GIF Optimization
Since Kraken API supports GIF to PNG8 conversion and optimization (if it happens to occupy less disk space) your static GIF images will be returned as optimized PNG files. In this case you have to change file extensions in your websites or applications. Optimized GIF animations will be returned as standard GIF animation files.
Downloading Images
Remember - never link to optimized images offered to download! You have to download them to your disk first, and then replace in your websites or applications. Files to download from Kraken are available on our servers for one hour.
Examples below show how you can pass your image URL for optimization in various programming languages and parse the response body.
Node.js
The easiest way to use Kraken API in Node.js is via NPM module called (surprisingly) Kraken. You can fork this module on GitHub or just install it with...
npm install kraken
...and then use in the following way:
var Kraken = require('kraken');
var kraken = new Kraken({
'user': 'your-kraken-username',
'pass': 'your-kraken-password',
'apikey': 'your-kraken-api-key'
});
var image = {
'url': 'http://image-url-to-optimize'
};
kraken.optimize(image, function(status) {
if (status.success) {
console.log('Success. Optimized image URL: %s', status.krakedURL);
} else {
console.log('Fail. Error message: %s', status.error);
}
});With this nifty module you can also optimize images via direct file upload.
PHP
<?php
$url = "https://api.kraken.io";
$data = array(
"auth" => array(
"user" => "your-kraken-username",
"pass" => "your-kraken-password",
"apikey" => "your-kraken-api-key"
),
"image" => array(
"url" => "http://awesome-website.com/images/header.png"
)
);
$data_string = json_encode($data);
$ch = curl_init();
$arr = array();
array_push($arr, 'Content-Type: application/json;');
curl_setopt($ch, CURLOPT_HTTPHEADER, $arr);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
$response = json_decode(curl_exec($ch));
curl_close($ch);
if ($response -> {'success'}) {
echo 'Success. Optimized image URL: ' . $response -> {'krakedURL'};
} else {
echo 'Fail. Error message: ' . $response -> {'error'};
}
?>Ruby
require 'net/http'
require 'net/https'
require 'json'
uri = URI.parse("https://api.kraken.io")
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
path = '/'
data = {
"auth" => {
"user" => "your-kraken-username",
"pass" => "your-kraken-password",
"apikey" => "your-kraken-api-key"
},
"image" => {
"url" => "http://awesome-website.com/images/header.png"
}
}.to_json
headers = {
'Content-Type' => 'application/json'
}
res, data = https.post(path, data, headers)
response = JSON.parse(res.body)
if response['success']
puts 'Success. Optimized image URL: ' + response['krakedURL']
else
puts 'Fail. Error message: ' + response['error']
endActionScript 3
// NOTE: You will need `as3corelib` for JSON serialization:
// https://github.com/mikechambers/as3corelib
package {
import flash.display.Sprite;
import flash.events.*;
import flash.net.*;
import com.adobe.serialization.json.JSON;
public class Kraken extends Sprite {
var _urlLoader:URLLoader,
_req:URLRequest,
_header:URLRequestHeader;
public function Kraken() {
this.init();
}
private function init():void {
_urlLoader = new URLLoader();
_req = new URLRequest();
_header = new URLRequestHeader("Content-Type", "application/json");
var auth:Object = new Object();
auth.user = 'your-kraken-username';
auth.pass = 'your-kraken-password';
auth.apikey = 'your-kraken-api-key';
var image:Object = new Object();
image.url = 'http://awesome-website.com/images/header.png';
_req.data = JSON.encode({ "auth": auth, "image": image });
_req.url = "https://api.kraken.io";
_req.method = URLRequestMethod.POST;
_req.requestHeaders.push(_header);
_urlLoader.addEventListener(Event.COMPLETE, onCompleteHandler);
_urlLoader.load(_req);
}
private function onCompleteHandler(e:Event):void {
var res = JSON.decode(e.target.data);
if (res.success) {
trace('Success. Optimized image URL:', res.krakedURL);
} else {
trace('Fail. Error message:', res.error);
}
}
}
}Python
import urllib
import urllib2
import json
parameters = {
'auth': {
'user': 'your-kraken-username',
'pass': 'your-kraken-password',
'apikey': 'your-kraken-api-key'
},
'image': {
'url': 'http://awesome-website.com/images/header.png'
}
}
headers = {
'Content-Type': 'application/json'
}
url = 'https://api.kraken.io'
data = json.dumps(parameters)
request = urllib2.Request(url, data, headers)
response = urllib2.urlopen(request)
jsonRes = json.loads(str(response.read()))
if (jsonRes['success']):
print 'Success. Optimized image URL: %s ' % jsonRes['krakedURL']
else:
print 'Fail. Error message: %s ' % jsonRes['error']Perl
# NOTE: You will need `JSON` library from CPAN:
# $ cpan
# cpan[1]> install JSON
use JSON;
use HTTP::Request::Common qw(POST);
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $url = 'https://api.kraken.io';
my $data = {
auth => {
user => 'your-kraken-username',
pass => 'your-kraken-password',
apikey => 'your-kraken-api-key'
},
image => {
url => 'http://awesome-website.com/images/header.png'
}
};
my $json_string = to_json($data);
my $req = HTTP::Request->new('POST', $url);
$req->header('Content-Type' => 'application/json');
$req->content($json_string);
my $res = $ua->request($req)->decoded_content;
my $decoded_json = decode_json($res);
if ($decoded_json->{'success'}) {
print 'Success. Optimized image URL: '.$decoded_json->{'krakedURL'}
} else {
print 'Fail. Error message: '.$decoded_json->{'error'};
}Examples below show how you can upload your image file directly to Kraken API in various programming languages and parse the response body.
Node.js
The easiest way to use Kraken API in Node.js is via NPM module called (surprisingly) Kraken. You can fork this module on GitHub or just install it with...
npm install kraken
...and then use in the following way:
var Kraken = require('kraken');
var kraken = new Kraken({
'user': 'your-kraken-username',
'pass': 'your-kraken-password',
'apikey': 'your-kraken-api-key'
});
var image = '/Path/To/File.jpg';
kraken.upload(image, function(status) {
if (status.success) {
console.log('Success. Optimized image URL: %s', status.krakedURL);
} else {
console.log('Fail. Error message: %s', status.error);
}
});PHP
<?php
$data = array(
'userfile' => '@/Path/To/File.jpg',
'auth' => '{
"user": "your-kraken-username",
"pass": "your-kraken-password",
"apikey": "your-kraken-api-key"
}'
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://api.kraken.io/file");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = json_decode(curl_exec($curl));
curl_close($curl);
if ($response -> {'success'}) {
echo 'Success. Optimized image URL: ' . $response -> {'krakedURL'};
} else {
echo 'Fail. Error message: ' . $response -> {'error'};
}
?>Ruby
# NOTE: You will need `multipart-post` gem:
# $ gem install multipart-post
require 'rubygems'
require 'json'
require 'net/https'
require 'net/http/post/multipart'
url = URI.parse("https://api.kraken.io/file")
uploadfile = {:name =>'/Path/To/File.jpg'}
auth = {
"user" => "your-kraken-username",
"pass" => "your-kraken-password",
"apikey" => "your-kraken-api-key"
}.to_json
File.open(uploadfile[:name]) do |file|
req = Net::HTTP::Post::Multipart.new url.path,
"auth" => auth,
"file" => UploadIO.new(file, 'logotyp.png')
https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true
res = https.start() {|conn| conn.request(req)}
response = JSON.parse(res.body)
if response['success']
puts 'Success. Optimized image URL: ' + response['krakedURL']
else
puts 'Fail. Error message: ' + response['error']
end
endActionScript 3
// NOTE: You will need `as3corelib` for JSON serialization:
// https://github.com/mikechambers/as3corelib
// Due to Flash security policy you can not choose
// file to upload directly via file path. This example assumes
// you have button `uploadBtn` on your Stage to browse the files on disk.
package {
import flash.display.Sprite;
import flash.display.LoaderInfo;
import flash.net.*;
import flash.events.*;
import com.adobe.serialization.json.JSON;
public class Kraken extends Sprite {
var fileRef:FileReferenceList = new FileReferenceList(),
auth:Object;
public function Kraken():void {
auth = new Object();
auth.user = 'your-kraken-username';
auth.pass = 'your-kraken-password';
auth.apikey = 'your-kraken-api-key';
this.init();
}
private function init():void {
uploadBtn.addEventListener('click', onFileClick);
}
private function onFileClick(e:MouseEvent):void {
var desc = "PNG, JPEG and GIF files",
type = "*.jpeg; *.jpg; *.png; *.gif;",
imageFilter:FileFilter = new FileFilter(desc, type);
fileRef.addEventListener(Event.SELECT, onFileSelected);
fileRef.browse([imageFilter]);
}
private function onFileSelected(e:Event):void {
uploadSingleFile(fileRef.fileList[0]);
}
private function uploadSingleFile(file:FileReference):void {
var urlScript:String = 'https://api.kraken.io/file',
urlReq:URLRequest = new URLRequest(urlScript),
urlVars:URLVariables = new URLVariables();
urlVars.auth = JSON.encode(auth);
urlReq.method = URLRequestMethod.POST;
urlReq.data = urlVars;
file.addEventListener(IOErrorEvent.IO_ERROR, onFileUploadError);
file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, uploadDataComplete);
file.upload(urlReq);
}
private function uploadDataComplete(e:DataEvent):void {
var res = JSON.decode(e.data);
if (res.success) {
trace('Success. Optimized image URL:', res.krakedURL);
} else {
trace('Fail. Error message:', res.error);
}
}
private function onFileUploadError(e:Event):void {
trace(e);
}
}
}Python
# NOTE: You will need `requests` module:
# $ pip install requests
# or
# $ easy_install requests
import requests
import json
uploadfile = open('/Path/To/File.jpg')
auth = json.dumps({
'user': 'your-kraken-username',
'pass': 'your-kraken-password',
'apikey': 'your-kraken-api-key'
});
request = requests.post(
url = 'https://api.kraken.io/file',
data = { 'auth': auth },
files = { 'file': uploadfile }
)
jsonRes = json.loads(str(request.content))
if (jsonRes['success']):
print 'Success. Optimized image URL: %s ' % jsonRes['krakedURL']
else:
print 'Fail. Error message: %s ' % jsonRes['error']Perl
# NOTE: You will need `JSON` library from CPAN:
# $ cpan
# cpan[1]> install JSON
use JSON;
use HTTP::Request::Common;
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $file = '/Path/To/File.jpg';
my $url = 'https://api.kraken.io/file';
my $auth = to_json({
user => 'your-kraken-username',
pass => 'your-kraken-password',
apikey => 'your-kraken-api-key'
});
my $res = $ua->request(
POST $url,
Content_Type => 'form-data',
Content => [uploadfile => ["$file"], auth => $auth]
);
my $decoded_json = decode_json($res->content);
if ($decoded_json->{'success'}) {
print 'Success. Optimized image URL: '.$decoded_json->{'krakedURL'}
} else {
print 'Fail. Error message: '.$decoded_json->{'error'};
}