You need to enable JavaScript to run this app.
Lake AI Service

Lake AI Service

Copy page
Download PDF
Image processing
Image cropping
Copy page
Download PDF
Image cropping

Operator introduction

Description

An image cropping processor that supports multiple cropping methods and various input and output formats.

Key features

  • Input formats:
    • URL address (image_url)
    • Base64 encoding (image_base64)
    • Binary stream (image_binary)
  • Crop methods (supports multiple algorithms and modes):
    • Coordinate cropping: Precisely crops by specifying the top-left and bottom-right coordinates.
    • Ratio cropping: Crops according to width and height ratio (0–1).
    • Center cropping: Crops from the center of the image with specified dimensions.
  • Interpolation algorithms: nearest, bilinear, bicubic, lanczos (used for resizing after cropping).
  • Output modes:
    • Returns the Base64 string of the cropped image.
    • Optionally saves the image to TOS.
    • Optionally saves the image to a local directory.
  • Format adaptation:
    • JPEG: Converts RGBA to RGB and applies quality compression.
    • PNG: Preserves the alpha channel and uses lossless compression.
    • WebP: Supports the alpha channel and uses quality or lossless compression.

Caution and prerequisites

Details

Caution and prerequisites

Costs

Before calling an operator, you need to understand the model invocation costs associated with using the operator. For details, see Large model invocation billing.

Authentication (API Key)

Before calling an operator, you need to generate an API Key for operator invocation. It is recommended to configure the API Key as an environment variable to ensure safer operator calls. For details, see Obtain and configure API Key.

BaseURL

Before calling an operator, you need to determine the BaseURL for operator invocation based on the region where your current LAS service is deployed. This is used to configure the path parameter values for operator calls.
For details, see Obtain the Base URL. The Examples below are for reference only; when making actual calls, replace the path values with those corresponding to your region.

Daft invocation

Operator parameters

Input

Input column name

Description

image

An array containing input images. Supports URL, Base64, and binary formats.

image_name

Optional parameter. An array containing image identifiers, used to generate output file names.

Output

An array of dictionaries containing processing results. Each element includes:

  • base64: Base64-encoded cropped image;
  • image_path: Local or TOS storage path (valid when output directory is configured).

Parameters

If a parameter does not have a default value, it is required.

Parameter name

Type

Default value

Description

image_suffix

str

.jpg

Suffix of the output file.
Description: File suffix used when saving to TOS or locally. Must be a supported format.
Optional values: [".jpg", ".jpeg", ".png", ".webp"]
Default value: ".jpg"

output_dir

str

""

Output folder path for saving images.
Description: Output path where the cropped image will be saved. If empty, the output will not be saved. Supports TOS and local paths.
Default value: ""

image_src_type

str

image_url

Input image format type.
Optional values: ["image_url", "image_base64", "image_binary"]
Default value: "image_url"

crop_type

str

center

Crop method.
Description: Supports three cropping modes, which must be used with the corresponding parameters:

  • coordinate: Must specify crop_coords=[x1, y1, x2, y2]
  • ratio: Must specify crop_ratio=[width_ratio, height_ratio] (0–1)
  • center: Must specify crop_size=[width, height] (or use the default ratio)

Optional values: ["coordinate", "ratio", "center"]
Default value: "center"

crop_coords

list

None

Coordinate cropping parameters.
Description: [x1, y1, x2, y2], x1/y1 = coordinates of the upper left corner, x2/y2 = coordinates of the lower right corner.
Default value: None

crop_ratio

list

[0.8, 0.8]

Proportional cropping parameter.
Description: [width_ratio, height_ratio], value range 0–1 (for example, [0.8, 0.8] crops 80% of the area).
Default value: [0.8, 0.8]

crop_size

list

None

Center cropping parameter.
Description: [width, height], specifies the width and height after cropping. If None, crops 80% of the original size.
Default value: None

quality

int

85

Save quality parameter (adapted for different formats):

  • JPEG/WebP: 1–100 (the higher the value, the better the quality)
  • PNG: mapped to compress_level (1→9, 100→0)

Default value: 85

method

str

lanczos

Interpolation algorithm (used when resizing after cropping).
Optional values: ["nearest", "bilinear", "bicubic", "lanczos"]
Default value: "lanczos"

Examples

The following code demonstrates how to use daft to run the operator for image cropping.

from __future__ import annotations

import os

import daft
from daft import col
from daft.las.functions.image.image_crop import ImageCrop
from daft.las.functions.udf import las_udf

if __name__ == "__main__":
    # Content will be saved to the specified TOS path. Therefore, you need to set environment variables to ensure permission to write to TOS, including: ACCESS_KEY, SECRET_KEY, TOS_ENDPOINT, TOS_REGION, TOS_TEST_DIR

    TOS_DIR = os.getenv("TOS_TEST_DIR", "tos_bucket")
    output_tos_dir = f"tos://{TOS_DIR}/image/image_crop"

    if os.getenv("DAFT_RUNNER", "native") == "ray":
        import logging

        import ray

        def configure_logging():
            logging.basicConfig(
                level=logging.INFO,
                format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
                datefmt="%Y-%m-%d %H:%M:%S.%s".format(),
            )
            logging.getLogger("tracing.span").setLevel(logging.WARNING)
            logging.getLogger("daft_io.stats").setLevel(logging.WARNING)
            logging.getLogger("DaftStatisticsManager").setLevel(logging.WARNING)
            logging.getLogger("DaftFlotillaScheduler").setLevel(logging.WARNING)
            logging.getLogger("DaftFlotillaDispatcher").setLevel(logging.WARNING)

        ray.init(dashboard_host="0.0.0.0", runtime_env={"worker_process_setup_hook": configure_logging})
        daft.set_runner_ray()

    daft.set_execution_config(actor_udf_ready_timeout=600)
    daft.set_execution_config(min_cpu_per_task=0)

    tos_dir_url = os.getenv("TOS_DIR_URL", "las-cn-beijing-public-online.tos-cn-beijing.volces.com")
    samples = {
        "image": [f"https://{tos_dir_url}/public/shared_image_dataset/cat.png"],
        "image_name": ["cat_crop_test"],
    }

    image_suffix = ".jpg"
    image_src_type = "image_url"
    crop_type = "center"
    crop_size = [500, 500]
    crop_ratio = [0.8, 0.8]
    crop_coords = [100, 100, 800, 800]
    quality = 85
    method = "lanczos"
    local_dir = ""

    ds = daft.from_pydict(samples)
    ds = ds.with_column(
        "image_crop",
        las_udf(
            ImageCrop,
            construct_args={
                "image_suffix": image_suffix,
                "output_dir": output_tos_dir,
                "image_src_type": image_src_type,
                "crop_type": crop_type,
                "crop_size": crop_size,
                "quality": quality,
                "method": method,
            },
            batch_size=1,
        )(col("image"), col("image_name")),
    )
    ds.show()
# ╭────────────────────────────────┬───────────────┬────────────────────────────────────────────╮
# │ image                          ┆ image_name    ┆ image_crop                                 │
# │ ---                            ┆ ---           ┆ ---                                        │
# │ String                         ┆ String        ┆ Struct[base64: String, image_path: String] │
# ╞════════════════════════════════╪═══════════════╪════════════════════════════════════════════╡
# │ https://las-ai-qa-online.tos-… ┆ cat_crop_test ┆ {base64: /9j/4AAQSkZJRgABAQAA…             │
# ╰────────────────────────────────┴───────────────┴────────────────────────────────────────────╯
Last updated: 2026.05.24 15:21:01