MERGE API Endpoint

Version 2.197 (Release Notes ↗)

Description

Merge multiple images with specified offsets, ideal for integrating with media analysis endpoints like FaceDetect and FaceLandmarks to create Snapchat-like filters. Check the sample page for usage examples. Composite as much images as desired on top of another at a specified offset. This API endpoint is of particular interest if mixed with some media analysis endpoints such as facedetect or docscan in order to mimic the Snapachat filters effects for example. Refer to the sample page for a concrete usage.

HTTP Methods

POST

HTTP Parameters

Required

Fields Type Description
src URL Target image URL. This is the composited image. If you want to upload your image directly from your app, call store and use the output link before invoking merge.
cord Array JSON array holding the coordinates of the images to be merged with the target (Array fields are described below).
key String Your PixLab API Key ↗. You can also embed your key in the WWW-Authenticate: HTTP header and omit this parameter if you want to.

Optional

Fields Type Description
blob Boolean By default, this API endpoint returns a JSON Object holding the link to the image output. If set to true, the image binary contents are returned instead.

POST Request Body

Allowed Content-Types:

application/json

Only JSON data is accepted. The cord parameter must be a JSON array containing object coordinates for each image to be composited on the target. Obtain these offsets from analysis API endpoints like docscan.

Fields Type Description
img URL Image URL to composite on the source. For direct uploads, call store first and use its output link.
x Integer X (column) coordinate offset for the composited image.
y Integer Y (row) coordinate offset for the composited image.
center Boolean When True, centers the image horizontally (X = Width/2) at the specified X offset.
center_y Boolean When True, centers the image vertically (Y = Height/2) at the specified Y offset.

A typical cord array:

cord = [
    {
     img: 'http://www.wowpng.com/wp-content/uploads/2016/10/lol-troll-face-png-image-october-2016-370x297.png',
      x: 200,
      y: 290
    },
    {
     img: 'http://orig08.deviantart.net/67d1/f/2010/216/6/7/lol_face_by_bloodyhalfdemon.png',
      x: 165,
      y: 95
    }
]

Tip: Use meme to add text overlays to your composited image.

HTTP Response

Fields Type Description
status Integer Status code 200 indicates success, any other code indicates failure.
link URL Link to the media output stored on pixlab.xyz storage unless custom S3 keys are configured (see console for setup).
id String Unique media identifier.
error String Error description when status ≠ 200.

Returns application/json when the optional blob parameter is omitted. Binary image data is returned directly when blob is enabled. The JSON response structure is documented above.

Code Samples


import requests
import json
from typing import Dict, Any, List

def composite_images(
    base_image_url: str,
    overlay_images: List[Dict[str, Any]],
    api_key: str
) -> str:
    """Composite multiple images onto a base image using PixLab API.
    
    Args:
        base_image_url: URL of the base image.
        overlay_images: List of dictionaries containing overlay image details.
        api_key: PixLab API key.
    
    Returns:
        URL of the composited image if successful, otherwise raises an exception.
    """
    endpoint = 'https://api.pixlab.io/merge'
    headers = {'Content-Type': 'application/json'}
    
    payload = {
        'src': base_image_url,
        'key': api_key,
        'cord': overlay_images
    }
    
    try:
        response = requests.post(
            endpoint,
            headers=headers,
            data=json.dumps(payload),
            timeout=10
        )
        response.raise_for_status()
        data = response.json()
        
        if data['status'] != 200:
            raise ValueError(f"API Error: {data.get('error', 'Unknown error')}")
        
        return data['link']
    
    except requests.exceptions.RequestException as e:
        raise ConnectionError(f"Request failed: {str(e)}") from e
    except json.JSONDecodeError as e:
        raise ValueError("Invalid JSON response from API") from e

# Example usage
if __name__ == "__main__":
    try:
        result_url = composite_images(
            base_image_url='https://pbs.twimg.com/media/CcEfpp0W4AEQVPf.jpg',
            overlay_images=[
                {
                    'img': 'http://www.wowpng.com/wp-content/uploads/2016/10/lol-troll-face-png-image-october-2016-370x297.png',
                    'x': 30,
                    'y': 320
                },
                {
                    'img': 'http://orig08.deviantart.net/67d1/f/2010/216/6/7/lol_face_by_bloodyhalfdemon.png',
                    'x': 630,
                    'y': 95
                }
            ],
            api_key='My_PIXLAB_API_KEY'
        )
        print(f"Composite image: {result_url}")
    except Exception as e:
        print(f"Error: {str(e)}")
← Return to API Endpoint Listing