Image Crop API for Smart Cropping and Resizing

Image Crop API for Smart Cropping and Resizing

用于智能裁剪与调整大小的 Image Crop API

Every App Needs Image Resizing. User uploads a 4000x3000 photo. Your thumbnail needs to be 200x200. Your product listing needs 800x600. Your social share card needs 1200x630. The original image fits none of these. You could install Sharp, write the resizing logic, handle edge cases (what if the image is portrait? what if it’s smaller than the target?), deploy it, and maintain the server. Or you could make one API call. The Iteration Layer’s Image Transformation API resizes and crops images in the cloud. Send an image, define your operations, get the result back. No server, no library, no Docker container.

每个应用都需要图像调整大小功能。用户上传了一张 4000x3000 的照片,但你的缩略图需要 200x200,产品列表需要 800x600,社交分享卡片需要 1200x630。原始图像无法直接适配这些尺寸。你本可以安装 Sharp 库、编写调整大小的逻辑、处理各种边缘情况(比如图像是纵向的怎么办?如果图像比目标尺寸小怎么办?)、部署并维护服务器。或者,你也可以只调用一次 API。Iteration Layer 的图像转换 API 可以在云端完成图像的调整大小和裁剪。只需发送图像,定义操作,即可获取结果。无需服务器、无需库、无需 Docker 容器。

Resize: Five Fit Strategies

调整大小:五种适配策略

The resize operation takes a target width, height, and a fit strategy that determines how the image fills the target dimensions:

调整大小操作需要目标宽度、高度以及一种适配策略,该策略决定了图像如何填充目标尺寸:

import { IterationLayer } from "iterationlayer";
const client = new IterationLayer({ apiKey: "YOUR_API_KEY", });
const { data: { buffer: imageBase64 } } = await client.transformImage({
  file: { type: "url", name: "photo.jpg", url: "https://example.com/photo.jpg", },
  operations: [
    { type: "resize", width_in_px: 800, height_in_px: 600, fit: "cover", },
  ],
});
{
  "success": true,
  "data": {
    "buffer": "/9j/4AAQSkZJRgABAQAAAQ...",
    "mime_type": "image/jpeg"
  }
}

The five fit strategies: 五种适配策略如下:

  • cover — scales the image to fill the target dimensions, cropping any overflow. The result is exactly width x height with no empty space. Best for thumbnails and cards where you need an exact size.
  • cover — 将图像缩放以填满目标尺寸,并裁剪掉溢出部分。结果正好是指定的宽高,没有空白区域。最适合需要精确尺寸的缩略图和卡片。
  • contain — scales the image to fit entirely within the target dimensions, adding letterboxing if the aspect ratios don’t match. The result is at most width x height. Best when you need the full image visible.
  • contain — 将图像缩放以完全适配目标尺寸,如果宽高比不匹配,则添加黑边(信箱模式)。结果最大为指定的宽高。最适合需要完整显示图像的场景。
  • fill — stretches the image to exactly width x height, ignoring aspect ratio. Best for backgrounds or abstract patterns where distortion doesn’t matter.
  • fill — 将图像拉伸至精确的宽高,忽略宽高比。最适合背景或不介意变形的抽象图案。
  • inside — scales down to fit within the target dimensions, preserving aspect ratio, never upscaling. The result may be smaller than the target. Best for constraining maximum dimensions.
  • inside — 在保持宽高比的前提下缩小图像以适配目标尺寸,从不放大。结果可能小于目标尺寸。最适合用于限制最大尺寸。
  • outside — scales so the image covers the target dimensions, preserving aspect ratio, never downscaling. The result may be larger than the target. Best when you want to guarantee minimum dimensions.
  • outside — 缩放图像以覆盖目标尺寸,保持宽高比,从不缩小。结果可能大于目标尺寸。最适合需要保证最小尺寸的场景。

Choosing the Right Fit Strategy

选择合适的适配策略

The fit strategy you pick depends on what you’re building. Here’s how each one maps to common use cases.

你选择的适配策略取决于你的构建目标。以下是每种策略对应的常见用例:

  • cover for thumbnails and cards. When you need a grid of identically-sized images — product listings, team member cards, gallery thumbnails — cover guarantees every image is the exact same dimensions. The tradeoff is that parts of the image may be cropped. For product photos shot against clean backgrounds, the crop is usually imperceptible. For portraits, combine cover with smart_crop to keep faces visible.
  • cover 用于缩略图和卡片。 当你需要一个尺寸统一的图像网格(如产品列表、团队成员卡片、画廊缩略图)时,cover 能保证每张图像的尺寸完全一致。代价是图像的部分内容可能会被裁剪。对于在干净背景下拍摄的产品照片,裁剪通常难以察觉。对于人像,可以将 cover 与 smart_crop 结合使用,以确保人脸可见。
  • contain for previews and lightboxes. When users expect to see the entire image — document previews, artwork displays, lightbox modals — contain preserves everything. The image sits within a bounding box, so you may get letterboxing (bars on the sides or top/bottom). Pair it with the extend operation and a background color to fill the letterbox area with a solid color instead of transparency.
  • contain 用于预览和灯箱。 当用户期望看到完整图像时(如文档预览、艺术品展示、灯箱模态框),contain 可以保留所有内容。图像位于边界框内,因此可能会出现黑边(侧边或顶部/底部)。将其与 extend 操作和背景色配合使用,可以用纯色填充黑边区域,而不是显示透明。
  • inside for upload constraints. When users upload images and you need to cap the dimensions without upscaling small images, inside is the right fit. A 4000x3000 photo resized with inside at 1920x1080 becomes 1440x1080. A 800x600 photo stays at 800x600. This is what you want for content management systems where you need to limit bandwidth without distorting smaller images.
  • inside 用于上传限制。 当用户上传图像且你需要限制尺寸但又不希望放大较小的图像时,inside 是最佳选择。一张 4000x3000 的照片使用 inside 调整为 1920x1080 后会变成 1440x1080,而 800x600 的照片则保持不变。这正是内容管理系统所需要的,既能限制带宽,又不会使较小的图像变形。
  • outside for minimum size guarantees. When a downstream process requires a minimum resolution — print workflows, large-format displays — outside ensures the image is at least the target dimensions. The result may be larger, which you can then crop to exact size.
  • outside 用于保证最小尺寸。 当下游流程需要最低分辨率时(如打印工作流、大幅面显示),outside 可确保图像至少达到目标尺寸。结果可能更大,之后你可以将其裁剪为精确尺寸。

Crop: Extract a Region

裁剪:提取区域

The crop operation extracts a rectangular region from the image:

crop 操作从图像中提取一个矩形区域:

const operations = [
  { type: "crop", left_in_px: 100, top_in_px: 50, width_in_px: 500, height_in_px: 400, },
];

This cuts a 500x400 rectangle starting at position (100, 50) from the top-left corner. Useful when you know exactly which region of the image you need. Manual crop is common in image editors and annotation tools where the user draws a selection rectangle. Your frontend captures the coordinates, and the API does the extraction.

这会从左上角 (100, 50) 位置开始切割出一个 500x400 的矩形。当你确切知道需要图像的哪个区域时,这非常有用。手动裁剪常见于图像编辑器和标注工具中,用户在这些工具中绘制选择矩形。你的前端捕获坐标,API 则负责执行提取。

Smart Crop: Let AI Find the Subject

智能裁剪:让 AI 寻找主体

Manual cropping requires knowing where the subject is. The smart_crop operation handles that automatically — it uses AI object detection to find the main subject (a face, a product, a focal point) and crops around it:

手动裁剪需要知道主体在哪里。smart_crop 操作可以自动处理——它使用 AI 对象检测来寻找主要主体(人脸、产品、焦点)并围绕它进行裁剪:

const operations = [
  { type: "smart_crop", width_in_px: 400, height_in_px: 400, },
];

The result is a 400x400 image with the subject centered. No coordinate math, no face detection library, no guesswork about where to crop. Smart crop is particularly useful for:

结果是一张主体居中的 400x400 图像。无需坐标计算,无需人脸检测库,无需猜测裁剪位置。Smart crop 特别适用于:

  • Profile pictures — always centers the face
  • 头像——始终将人脸居中
  • Product thumbnails — keeps the product in frame regardless of the original composition
  • 产品缩略图——无论原始构图如何,都能将产品保持在画面内
  • Content cards — finds the focal point of editorial images
  • 内容卡片——寻找编辑图像的焦点

The difference between resize with cover and smart_crop is intelligence. cover crops from the center. smart_crop crops around the detected subject. For images where the subject isn’t centered — a person standing to the left, a product in the bottom-right corner — smart crop produces noticeably better results.

resize 的 cover 模式与 smart_crop 的区别在于智能性。cover 从中心裁剪,而 smart_crop 围绕检测到的主体裁剪。对于主体不在中心位置的图像(例如站在左侧的人、位于右下角的产品),smart_crop 能产生明显更好的效果。

Responsive Images with Resize

使用 Resize 实现响应式图像

Modern web development requires multiple sizes of every image. A hero image might need five variants for different screen widths. The resize operation handles this naturally:

现代 Web 开发要求每张图像都有多种尺寸。一张首屏大图(Hero image)可能需要针对不同屏幕宽度提供五个变体。resize 操作可以自然地处理这一点:

import { IterationLayer } from "iterationlayer";
const client = new IterationLayer({ apiKey: "YOUR_API_KEY", });
const widths = [320, 640, 960, 1280, 1920];
const variants = await Promise.all(
  widths.map(async (width) => {
    const { data: { buffer } } = await client.transformImage({
      file: { type: "url", name: "hero.jpg", url: sourceUrl, },
      operations: [
        { type: "resize", width_in_px: width, height_in_px: Math.round(width * 0.5625), fit: "cover", },
        { type: "convert", format: "webp" }
      ],
    });
    return buffer;
  })
);