Cropping

Image Operations / Image Cropping

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

With image cropping you can remove unwanted parts of the image or extract a portion of the image with the most interesting bits. The Pixaven Image API offers you two modes of image cropping: rect and face.

Rect

This mode allows you to extract a rectangular portion of the image by providing the width and height of the fragment you'd like to extract and optionally a gravity parameter. The default crop gravity is center and you may use one of the following values: top-left, top, top-right, right, bottom-right, bottom, bottom-left, left.

{
    "crop": {
        "mode": "rect",
        "width": 375,
        "height": 150,
        "gravity": "center"
    }
}
Given the input image 750px × 300px
Extract the default center portion of the image by setting "width" to 375 and "height" to 150
The resulting image is 375px × 150px cropped from the center

If you know the exact position of the fragment you'd like to extract, you may ignore the gravity parameter and specify x and y coordinates. The 0,0 point (the origin) is located at the top-left corner of the image.

{
    "crop": {
        "mode": "rect",
        "width": 375,
        "height": 150,
        "x": 340,
        "y": 100
    }
}
Given the input image 750px × 300px
Extract the portion of the image at x=340, y=100 by setting "width" to 375 and "height" to 150
The resulting image is 375px × 150px cropped at x=340, y=100

Face

With the face mode, you can leverage face detection algorithms and easily extract the portion of the image that contains a face. You may specify a padding parameter which takes an integer and describes the distance between the face and image bounds. The bigger the padding, the more space around the face will be visible on the output image.

{
    "crop": {
        "mode": "face",
        "padding": 100
    }
}

If there is more than one face detected on the image, the API will by default ensure that the extracted portion of the image will contain all the faces. You may alter this behavior by specifying an index parameter which takes an integer and describes which face to extract (read below). If no faces are detected, the API will return the input image or pass it to the next transformation step you've requested.

{
    "crop": {
        "mode": "face",
        "index": 1
    }
}

Lets have a look at a simple use-case. Say you'd like to perform a face crop and give the face a padding of 100px so that there are exactly 100 pixels in each direction between the face and image bounds.

{
    "crop": {
        "mode": "face",
        "padding": 100
    }
}
Given the input image 750px × 400px
Extract the portion of the image which contains a face and ensure 100px between the face and image bounds

As previously mentioned, when there is more than one face detected, the API will by default extract the portion of the image which contains all of the faces. Using the same settings as above "mode": "face", "padding": 100 you'll get the following output when the image with multiple faces is supplied:

Given the input image 750px × 400px
Extract the portion of the image which contains a face and ensure 100px between the face and image bounds

By setting an index parameter, you can select the face you'd like to extract. Faces are numbered in the left-to-right order starting from 1 so if you'd like to extract the face on the right you'd have to set 2 as the index value.

{
    "crop": {
        "mode": "face",
        "padding": 100,
        "index": 2
    }
}
Given the input image 750px × 400px
Extract the portion of the image which contains a face on the right and ensure 100px between the face and image bounds

Code Examples for Image Cropping

Below, you'll find examples of how to use Image Cropping from the Pixaven API:

<?php

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

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


/**
* Provide a publicly available image URL with fetch(string) method
* and extract a 375 x 150 portion of the image at top-right position
*/

$pix
    ->fetch('https://www.website.com/image.jpg')
    ->crop(array(
        'mode' => 'rect',
        'width' => 375,
        'height' => 150,
        'gravity' => 'top-right'
    ))
    ->toJSON(function ($error, $meta) {
        if (!empty($error)) {
            throw new Exception($error);
        }

        /**
        * You'll find the full JSON metadata array 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']);
        }
    });
/**
* Module dependencies
*/

const Pixaven = require("pixaven");


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

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


/**
* Provide a publicly available image URL with fetch(string) method
* and extract a 375 x 150 portion of the image at top-right position
*/

pix
    .fetch("https://www.website.com/image.jpg")
    .crop({
        mode: "rect",
        width: 375,
        height: 150,
        gravity: "top-right"
    })
    .toJSON((err, meta) => {
        if (err) {
            return console.log(err);
        }

        /**
        * 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);
        }
    });
##
# Require dependencies

require "pixaven"


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

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


##
# Provide a publicly available image URL with fetch(string) method
# and extract a 375 x 150 portion of the image at top-right position

err, meta = pix
    .fetch("https://www.website.com/image.jpg")
    .crop(
        mode: "rect",
        width: 375,
        height: 150,
        gravity: "top-right"
    )
    .to_json

abort(err) if err


##
# 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
package main

import (
    "fmt"
    "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)
    }


    /**
    * Provide a publicly available image URL with Fetch(string) method
    * and extract a 375 x 150 portion of the image at top-right position
    */

    meta, err := pix.
        Fetch("https://www.website.com/image.jpg").
        Crop(pixaven.P{
            "mode": "rect",
            "width": 375,
            "height": 150,
            "gravity": "top-right"
        }).
        ToJSON()

    if err != nil {
        panic(err)
    }


    /**
    * 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"])
    }
}
##
# Import dependencies

from pixaven import pixaven


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

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


##
# Provide a publicly available image URL with fetch(string) method
# and extract a 375 x 150 portion of the image at top-right position

err, meta = (
    client
        .fetch('https://www.website.com/image.jpg')
        .crop({
            'mode': 'rect',
            'width': 375,
            'height': 150,
            'gravity': 'top-right'
        })
        .toJSON()
)

if err is not None:
    raise StandardError(err)


##
# 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 static com.pixaven.OperationConfiguration.settings;
import com.pixaven.Pixaven;
import com.pixaven.Fetch;
import com.pixaven.Response;

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

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

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

        /**
        * Provide a publicly available image URL with fetch(String) method
        * and extract a 375 x 150 portion of the image at top-right position
        */

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

        fetch.crop(
            settings()
                .set("mode", "rect")
                .set("width", 375)
                .set("height", 150)
                .set("gravity", "top-right")
        );

        final Response response = fetch.toJson();

        /**
        * 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 (response.isSuccessful()) {
            System.out.println(response.getMetadata().getOutput().get("url"));
        } else {
            System.out.println(response.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×