Image function overview

Updated at:

This topic describes the limits, invocation rules, and image data forms of image functions, the built-in Flink SQL IMAGE type, and several image processing pipeline examples.

Limits

Supported only by Realtime Compute engine VVR 11.8 or later.

Usage

Usage notes

In SQL deployments on the platform, most image functions, such as IMAGE_DECODE, IMAGE_ENCODE, and IMAGE_RESIZE, are provided by the built-in python module, and no additional dependencies are required in the deployment. Before you use a function provided by the python module, load the module first and then enable the python and core modules:

LOAD MODULE python;
USE MODULES python, core;

Basic invocation

Image processing typically consists of three stages: decoding, processing, and encoding. Encoded image bytes are first decoded into IMAGE. Image processing functions are then called. Finally, the result is encoded into image bytes or a Data URL as required by downstream systems.

LOAD MODULE python;
USE MODULES python, core;

WITH decoded AS (
    SELECT
        id,
        IMAGE_DECODE(image_bytes, 'null', 'RGB') AS image_value
    FROM raw_images
)
SELECT
    id,
    IMAGE_METADATA(image_value).width AS width,
    IMAGE_METADATA(image_value).height AS height,
    IMAGE_ENCODE(
        IMAGE_RESIZE(image_value, 512, 512),
        'JPEG',
        85,
        'bytes'
    ) AS resized_image_bytes
FROM decoded
WHERE image_value IS NOT NULL;

Parameter passing

SQL functions take arguments in the order defined in the signature and support only positional arguments. In a function signature, [ ] indicates an optional parameter. For example, the signature of IMAGE_ENCODE is as follows:

IMAGE_ENCODE(image_input [, format [, quality [, output]]])

The following rules apply to invocation:

  • Omitted optional parameters are filled with their default values.

  • To explicitly set a later optional parameter, you must also explicitly specify all preceding optional parameters.

  • NULL is passed as a parameter value, which is not equivalent to the default value used when the parameter is omitted.

  • Except for per-row image inputs, such as image_bytes and image_input, and the data parameters explicitly marked in the function documentation, configuration parameters such as mode, format, size, threshold, and algorithm must use SQL literals. Table fields and CAST expressions are not supported.

Data types

Image data forms

Data in an image processing pipeline typically exists in the following three forms:

Data form

SQL type

Description

Encoded image

BYTES

Image file bytes in encoding formats such as JPEG, PNG, and WebP. Suitable for storage or transfer between connectors, tables, and external systems.

Decoded image

IMAGE

A built-in Flink SQL image type that stores decoded pixels and the required metadata. Mainly used as an intermediate data structure between image functions.

Data URL

STRING

A string in the form of data:image/...;base64,.... Can be previewed in a browser or passed to a downstream interface that supports Data URLs.

  • Different functions accept different data forms. Refer to the parameter table of each function.

  • The input type of most image processing functions is IMAGE. If the data source stores encoded image bytes, you usually need to call IMAGE_DECODE to decode them first. Only some boundary functions support BYTES or both input types.

  • Image encoding functions generally support the following encoding formats: JPEG, PNG, TIFF, WEBP, BMP, GIF.

Built-in IMAGE type

Type positioning

IMAGE represents a decoded static image. It contains the image pixel data and three metadata items: image mode, height, and width.

IMAGE does not retain the encoding format of the original image file, nor file-level metadata such as EXIF and ICC. Therefore, IMAGE is suitable as an intermediate data carrier during computation in built-in image functions or UDFs, but not as a field type for persistent reads and writes in external systems.

Type declaration

IMAGE may appear in the following forms in function return values, type inference, type display, or explicit conversion:

Type

Description

Example

IMAGE

Neither the image mode nor the size is fixed.

IMAGE

IMAGE('<mode>')

The image mode is fixed and the size is not fixed.

IMAGE('RGB')

IMAGE('<mode>', <height>, <width>)

Both the image mode and the exact size are fixed.

IMAGE('RGB', 224, 224)

In the preceding syntax, <mode> indicates the image mode, and <height> and <width> indicate the image height and width respectively. Type parameters describe the metadata of decoded pixels and also serve as constraints for validating actual data.

Image modes

The image mode determines the channel semantics, the number of channels, and the data type of each channel element. The following image modes are supported:

Mode

Channels

Channel type

Description

L

1

UINT8

8-bit grayscale image.

LA

2

UINT8

8-bit grayscale image with an alpha channel.

RGB

3

UINT8

8-bit RGB image.

RGBA

4

UINT8

8-bit RGB image with an alpha channel.

L16

1

UINT16

16-bit grayscale image.

The image mode and the encoding format of an image file are two different concepts. For example, RGB describes the decoded pixel channels, whereas JPEG and PNG describe the encoded file format.

Type conversion

  • IMAGE types support only conversions that relax constraints, such as IMAGE('RGB', 224, 224) -> IMAGE('RGB') -> IMAGE. Conversions that tighten or change constraints are not supported, such as IMAGE -> IMAGE('RGB') or IMAGE('RGB') -> IMAGE('L').

  • CAST(image_value AS STRING) outputs only a summary of the image metadata and cannot be used to preview the image. Sample output:

IMAGE(mode='RGB', height=224, width=224)

Image preview

Depending on whether the current data is a decoded IMAGE or encoded BYTES, you can generate a Data URL in either of the following two ways.

Preview a decoded IMAGE

For an IMAGE value, use the IMAGE_ENCODE output mode of 'data_url' to encode the image and convert it to Base64:

SELECT
    IMAGE_ENCODE(
        image_value,
        'JPEG',     -- Image encoding format, such as 'JPEG' or 'PNG'.
        85,         -- Image compression quality, which affects lossy formats such as 'JPEG' and 'WEBP'.
        'data_url'  -- 'bytes' outputs raw encoded bytes; 'data_url' outputs a Data URL.
    ) AS preview_url
FROM processed_images;

Preview encoded image bytes

If you already have the encoded image bytes and the corresponding MIME type, you do not need to decode and re-encode the image. Use TO_BASE64 to Base64-encode the image bytes, and then use CONCAT to concatenate the Data URL:

SELECT
    id,
    CONCAT(
        'data:',
        mime_type,
        ';base64,',
        TO_BASE64(image_bytes)
    ) AS preview_url
FROM encoded_images;

The generated result is similar to the following:

data:image/jpeg;base64,...
  • For a small image, copy the Data URL to the browser address bar to preview it.

  • For a large image, write the complete Data URL into an HTML file and view it as the img attribute of an src tag. Example:

<!doctype html>
<html>
  <body>
    <img src="data:image/jpeg;base64,..." />
  </body>
</html>

Pipeline examples

Basic example: standardize the size and generate output

The following example decodes raw image bytes into RGB images, resizes them uniformly to 512 × 512, and finally outputs the image metadata, JPEG bytes, and a Data URL for preview:

LOAD MODULE python;
USE MODULES python, core;

-- Step 1: Decode the raw images. Data that cannot be decoded returns NULL, which prevents a single corrupted record from interrupting the deployment.
WITH decoded AS (
    SELECT
        id,
        IMAGE_DECODE(
            image_bytes,
            'null',
            'RGB'
        ) AS image_value
    FROM raw_images
),
-- Step 2: Filter out records that failed to decode, and resize valid images uniformly to 512 × 512.
resized AS (
    SELECT
        id,
        IMAGE_RESIZE(
            image_value,
            512,
            512,
            'lanczos'
        ) AS image_value
    FROM decoded
    WHERE image_value IS NOT NULL
)
-- Step 3: Output the processed metadata, encoded bytes, and browser preview URL.
SELECT
    id,
    IMAGE_METADATA(image_value).mode AS image_mode,
    IMAGE_METADATA(image_value).width AS image_width,
    IMAGE_METADATA(image_value).height AS image_height,
    IMAGE_ENCODE(
        image_value,
        'JPEG',
        85,
        'bytes'
    ) AS image_bytes,
    IMAGE_ENCODE(
        image_value,
        'JPEG',
        85,
        'data_url'
    ) AS preview_url
FROM resized;

Scenario 1: standardize primary product images for e-commerce

Product images may have complex backgrounds or inconsistent sizes. The following example decodes product images, removes the original background and fills it with white, standardizes the images to 800 × 800 JPEG primary images, and finally generates preview URLs based on the encoded bytes:

LOAD MODULE python;
USE MODULES python, core;

-- Step 1: Decode product images into RGB. Corrupted images return NULL.
WITH decoded AS (
    SELECT
        sku_id,
        IMAGE_DECODE(
            image_bytes,
            'null',
            'RGB'
        ) AS image_value
    FROM product_images
),
-- Step 2: Remove the product background and use opaque white as the new background.
white_background AS (
    SELECT
        sku_id,
        IMAGE_REMOVE_BACKGROUND(
            image_value,
            FALSE,
            240,
            10,
            10,
            ARRAY[255, 255, 255, 255]
        ) AS image_value
    FROM decoded
    WHERE image_value IS NOT NULL
),
-- Step 3: Standardize the primary image size based on the product platform specifications.
standardized AS (
    SELECT
        sku_id,
        IMAGE_RESIZE(
            image_value,
            800,
            800,
            'lanczos'
        ) AS image_value
    FROM white_background
),
-- Step 4: Encode the standardized images into JPEG bytes for object storage or downstream tables.
encoded AS (
    SELECT
        sku_id,
        IMAGE_ENCODE(
            image_value,
            'JPEG',
            90,
            'bytes'
        ) AS image_bytes
    FROM standardized
)
-- Step 5: Retain the encoded bytes and generate preview URLs for the operations review page as needed.
SELECT
    sku_id,
    image_bytes,
    CONCAT(
        'data:image/jpeg;base64,',
        TO_BASE64(image_bytes)
    ) AS preview_url
FROM encoded;

Scenario 2: preprocess scanned documents for OCR

Scanned documents such as contracts and invoices often have black borders, color noise, or low contrast. The following example crops the black borders, converts the images to grayscale and enhances the contrast, performs OCR, and retains the preprocessed PNG images for result review:

LOAD MODULE python;
USE MODULES python, core;

-- Step 1: Decode each scanned page. Corrupted images return NULL.
WITH decoded AS (
    SELECT
        document_id,
        page_no,
        IMAGE_DECODE(
            image_bytes,
            'null',
            'RGB'
        ) AS image_value
    FROM scanned_document_pages
),
-- Step 2: Automatically detect and crop the black borders around the page.
cropped AS (
    SELECT
        document_id,
        page_no,
        IMAGE_CROP_BLACK_BORDER(
            image_value,
            'auto',
            10,
            1.0,
            1
        ) AS image_value
    FROM decoded
    WHERE image_value IS NOT NULL
),
-- Step 3: Convert to an 8-bit grayscale image to reduce the impact of color information on text recognition.
grayscale AS (
    SELECT
        document_id,
        page_no,
        IMAGE_CONVERT_MODE(
            image_value,
            'L'
        ) AS image_value
    FROM cropped
),
-- Step 4: Keep the brightness unchanged and increase the contrast to 1.25 times that of the original image.
enhanced AS (
    SELECT
        document_id,
        page_no,
        IMAGE_ADJUST_COLOR(
            image_value,
            1.0,
            1.25,
            1.0
        ) AS image_value
    FROM grayscale
)
-- Step 5: Recognize English text and retain the preprocessed images for manual review.
SELECT
    document_id,
    page_no,
    IMAGE_OCR(
        image_value,
        ARRAY['en']
    ) AS ocr_result,
    IMAGE_ENCODE(
        image_value,
        'PNG'
    ) AS preprocessed_image_bytes
FROM enhanced;