Binary Responses

HTTP Responses / Binary Responses

On this page:
Intro ▾
{{activeSubMenu.text}} ▾

The Pixaven API gives you the option to receive a full binary representation of the output (resulting) image as a response body. That way you can skip downloading the processed image and instead stream the response directly to disk. To use a Binary Response you must set the mode parameter to binary within the response hash in your JSON-formatted request and also send a X-Pixaven-Binary header along with your request.

X-Pixaven-Binary: 1

{
    "response": {
        "mode": "binary"
    }
}

It's worth noting that even when Binary Responses are in use, the API will still store the resulting image in Pixaven temporary storage and provide you with an image URL in JSON metadata. So even if you fail to stream back the API response (the resulting image), you will still have the option to download that image later on.

Let's assume you'd like to use the Image Fetch method (provide an image URL) and resize the image to 100×75 pixels. An example cURL request using a binary response will look like the following:

curl https://api.pixaven.com/1.0/fetch -X POST -u your-api-key: \
-H "Content-Type: application/json" \
-H "X-Pixaven-Binary: 1" \
-d '{
    "url": "https://www.website.com/image.jpg",
    "resize": {
        "width": 100,
        "height": 75
    },
    "response": {
        "mode": "binary"
    }
}' > /location/on/disk/image.jpg

As cURL by default sends the output to stdout, in the last line of the above example we redirect stdout and stream the response to a file /location/on/disk/image.jpg.

When using Binary Responses it is best to always rely on our official integrations as the above cURL example will stream all responses to disk (both successful AND unsuccessful). For example, when the API responds with 422 Unprocessable Entity, your /location/on/disk/image.jpg will be an empty file when using cURL from the command line. All of our official integrations guard against that behaviour and only stream the response to disk when the API responds with 200 OK.

Limitations

Binary responses will not work for requests using Webhooks, Pixaven Cloud Storage or any External Storage provider.

Request Metadata in a Binary Response

Because the response body will consist of a binary representation of the resulting image, for both successful and failed requests, the API will return serialized JSON metadata in a HTTP header named X-Pixaven-Metadata. In other words, when using Binary Responses, you must always parse the X-Pixaven-Metadata response header to get the metadata pertaining to your request.

Code Examples for Binary Responses

All official integrations for the Pixaven API support binary responses out of the box:

<?php

/**
* Pixaven PHP library exposes two methods by which you can use
* binary responses: toFile(string, fn) and toBuffer(fn)
*/


/**
* Instantiate new `$pix` by calling a constructor
*/

$pix = new Pixaven\Pixaven('your-api-key');


/**
* Example code for toFile(string, fn) method:
*/

$pix
    ->fetch('https://www.website.com/image.jpg')
    ->resize(array(
        'width' => 100,
        'height' => 75
    ))
    ->toFile('path/to/output.jpg', function ($error, $meta) {
        if (!empty($error)) {
            throw new Exception($error);
        }

        /**
        * The resulting image has been written to disk at `path/to/output.jpg`
        * You'll find the full JSON metadata hash within the `$meta` variable.
        * Remember to always check if the `success` property is set to `true`.
        */

        if ($meta['success'] == true) {
            print ($meta['output']['url']);
        } else {
            print ($meta['message']);
        }
    });


/**
* Example code for .toBuffer(fn) method:
*/

$pix
    ->fetch('https://www.website.com/image.jpg')
    ->resize(array(
        'width' => 100,
        'height' => 75
    ))
    ->toBuffer(function ($error, $meta, $buffer) {
        if (!empty($error)) {
            throw new Exception($error);
        }

        /**
        * Binary representation of the output image is stored within `$buffer` variable.
        * You'll find the full JSON metadata hash within the `meta` variable.
        * Remember to always check if the `success` property is set to `true`.
        */

        if ($meta['success'] == true) {
            print ($meta['output']['url']);
        } else {
            print ($meta['message']);
        }
    });
/**
* Pixaven Node module exposes two methods by which you can use
* binary responses: toFile(string|stream, fn) and toBuffer(fn)
*/


/**
* Module dependencies
*/

const Pixaven = require("pixaven");


/**
* Instantiate new `pix` by calling a constructor
*/

const pix = new Pixaven("your-api-key");


/**
* Example code for .toFile(string|stream, fn) method:
*/

pix
    .fetch("https://www.website.com/image.jpg")
    .resize({
        width: 100,
        height: 75
    })
    .toFile("path/to/output.jpg", (err, meta) => {
        if (err) {
            return console.log(err);
        }

        /**
        * The resulting image has been written to disk at `path/to/output.jpg`
        * You'll find the full JSON metadata hash within the `meta` variable.
        * Remember to always check if the `success` property is set to `true`.
        */

        if (meta.success) {
            console.log(meta.output.url);
        } else {
            console.log(meta.message);
        }
    });


/**
* Example code for .toBuffer(fn) method:
*/

pix
    .fetch("https://www.website.com/image.jpg")
    .resize({
        width: 100,
        height: 75
    })
    .toBuffer((err, meta, buff) => {
        if (err) {
            return console.log(err);
        }

        /**
        * Binary representation of the output image is stored within `buff` variable.
        * You'll find the full JSON metadata hash within the `$meta` variable.
        * Remember to always check if the `success` property is set to `true`.
        */

        if (meta.success) {
            console.log(meta.output.url);
        } else {
            console.log(meta.message);
        }
    });
##
# Pixaven Ruby Gem exposes two methods by which you can use
# binary responses: to_file(string) and to_buffer.


##
# Require dependencies

require "pixaven"


##
# Instantiate new `pix` by calling a constructor

pix = Pixaven.new("your-api-key")


##
# Example code for .to_file(string) method:

err, meta = pix
    .fetch("https://www.website.com/image.jpg")
    .resize(
        width: 100,
        height: 75
    )
    .to_file("path/to/output.jpg")

abort(err) if err


##
# The resulting image has been written to disk at `path/to/output.jpg`
# You'll find the full JSON metadata hash within the `meta` variable.
# Remember to always check if the `success` property is set to `true`.

if meta["success"]
    puts meta["output"]["url"]
else
    puts meta["message"]
end


##
# Example code for .to_buffer method:

err, meta, buff = pix
    .fetch("https://www.website.com/image.jpg")
    .resize(
        width: 100,
        height: 75
    )
    .to_buffer

abort(err) if err


##
# Binary representation of the output image is stored within `buff` variable.
# You'll find the full JSON metadata hash within the `meta` variable.
# Remember to always check if the `success` property is set to `true`.

if meta["success"]
    puts meta["output"]["url"]
else
    puts meta["message"]
end
/**
* Pixaven Golang package exposes two methods by which you can use
* binary responses: ToFile(string|io.WriteCloser) and ToBuffer().
*/

package main

import (
    "bytes"
    "fmt"
    "io"
    "github.com/pixaven/pixaven-go"
)

func main() {

    /**
    * Instantiate new `pix` by calling a constructor
    */

    pix, err := pixaven.NewClient("your-api-key")

    if err != nil {
        panic(err)
    }


    /*
    * Example code for .ToFile(string) method:
    */

    meta, err := pix.
        Fetch("https://www.website.com/image.jpg").
        Resize(pixaven.P{
            "width": 100,
            "height": 75
        }).
        ToFile("path/to/output.jpg")

    if err != nil {
        panic(err)
    }


    /**
    * The resulting image has been written to disk at `path/to/output.jpg`
    * You'll find the full JSON metadata hash within the `meta` variable.
    * Remember to always check if the `success` property is set to `true`.
    */

    if meta["success"].(map[string]interface{})["success"].(bool) {
        fmt.Println(meta["output"].(map[string]interface{})["url"])
    } else {
        fmt.Println(meta["message"])
    }


    /*
    * Example code for .ToBuffer() method:
    */

    meta, reader, err := pix.
        Fetch("https://www.website.com/image.jpg").
        Resize(pixaven.P{
            "width": 100,
            "height": 75
        }).
        ToBuffer()

    if err != nil {
        panic(err)
    }


    /**
    * Always remember to close reader to free up the connection.
    */

    if reader != nil {
        defer reader.Close()
    }


    /**
    * Binary representation of the output image is streamed from the `reader` variable.
    * You'll find the full JSON metadata hash within the `meta` variable.
    * Remember to always check if the `success` property is set to `true`.
    */

    if meta["success"].(map[string]interface{})["success"].(bool) {
        fmt.Println(meta["output"].(map[string]interface{})["url"])

        /**
        * File can be streamed using .Read, io.Copy etc., but sometimes it is easier
        * to use the io/ioutil package.
        */

        data, err := ioutil.ReadAll(reader)

        if err != nil {
            panic(err)
        }

        fmt.Println(data)
    } else {
        fmt.Println(meta["message"])
    }
}
##
# Pixaven Python package exposes two methods by which you can use
# binary responses: toFile(string) and toBuffer()


##
# Import dependencies

from pixaven import pixaven


##
# Instantiate new `client` by calling a constructor

client = pixaven('your-api-key')


##
# Example code for .toFile(string) method:

err, meta = (
    client
        .fetch('https://www.website.com/image.jpg')
        .resize({
            'width': 100,
            'height': 75
        })
        .toFile('path/to/output.jpg')
)

if err is not None:
    raise StandardError(err)


##
# The resulting image has been written to disk at `path/to/output.jpg`
# You'll find the full JSON metadata hash within the `meta` variable.
# Remember to always check if the `success` property is set to `true`.

if meta['success'] is True:
    print (meta['output']['url'])
else:
    print (meta['message'])


##
# Example code for .toBuffer() method:

err, meta, buff = (
    client
        .fetch('https://www.website.com/image.jpg')
        .resize({
            'width': 100,
            'height': 75
        })
        .toBuffer()
)

if err is not None:
    raise StandardError(err)


##
# Binary representation of the output image is stored within `buff` variable.
# You'll find the full JSON metadata hash within the `meta` variable.
# Remember to always check if the `success` property is set to `true`.

if meta['success'] is True:
    print (meta['output']['url'])
else:
    print (meta['message'])
package com.pixaven.examples;

/**
* Import dependencies
*/

import java.io.IOException;

import static com.pixaven.OperationConfiguration.settings;
import com.pixaven.Pixaven;
import com.pixaven.Fetch;
import com.pixaven.Response;
import com.pixaven.support.ByteSourceResponse;

public class BinaryResponses {
    public static void main(String[] args) {

        /**
        * Instantiate new `pix` by calling a constructor
        */

        Pixaven pix = new Pixaven("your-api-key");


        /**
        * Example code for .toFile() method:
        */

        final Fetch fetch = pix.fetch("https://www.website.com/image.jpg");

        fetch.resize(
            settings()
                .set("width", 100)
                .set("height", 75)
        );

        try {
            final Response response = fetch.toFile("path/to/output.jpg");

            /**
            * The resulting image has been written to disk at `path/to/output.jpg`
            * You'll find the full JSON metadata hash within the `metadata` property.
            * Remember to always check if the `successful` property is set to `true`.
            */

            if (response.isSuccessful()) {
                System.out.println(response.getMetadata().getOutput().get("url"));
            } else {
                System.out.println(response.getMessage());
            }
        } catch (IOException io) {
            // handle IOException
        }


        /**
        * Example code for .toBuffer() method.
        *
        * Note: Buffered response needs to by explicitly closed
        * that's why we need to use auto-resource management.
        */

        final Fetch fetch = pix.fetch("https://www.website.com/image.jpg");

        fetch.resize(
            settings()
                .set("width", 100)
                .set("height", 75)
        );

        try (final ByteSourceResponse buffered = fetch.toBuffer()) {

            /**
            * Binary representation of the output image is stored within `ByteSource` subclass.
            * You'll find the full JSON metadata hash within the `Response#getMetadata()` property.
            * Remember to always check if the `Response#successful` property is set to `true`.
            */

            if (buffered.isSuccessful()) {
                System.out.println(buffered.getMetadata().getOutput().get("url"));
            } else {
                System.out.println(buffered.getMessage());
            }
        }
    }
}

We use both proprietary and third-party cookies to improve your browsing experience and to provide you with a better service. By continuing to use this site you consent our use of cookies as described in our Cookie Policy×