跳转到内容
搜索文档

绘制叠加和水印

最后更新 查看 MarkdownAgent 设置

您可以在调整大小的图像上绘制额外的图像,支持透明度和混合效果。这可以在调整大小的图像上添加水印、徽标、签名、晕影和其他效果。

此功能仅在 Workers 中可用。要绘制叠加图像,请将绘制命令数组添加到 fetch() 请求的选项中。绘制选项嵌套在 options.cf.image.draw 中,如下例所示:

fetch(imageURL, {
	cf: {
		image: {
			width: 800,
			height: 600,
			draw: [
				{
					url: "https://example.com/branding/logo.png", // draw this image
					bottom: 5, // 5 pixels from the bottom edge
					right: 5, // 5 pixels from the right edge
					fit: "contain", // make it fit within 100x50 area
					width: 100,
					height: 50,
					opacity: 0.8, // 20% transparent
				},
			],
		},
	},
});

绘制选项

draw 属性是一个数组。叠加按数组中出现的顺序绘制(最后一个数组条目是最顶层)。draw 数组中的每个项是一个对象,可以具有以下属性:

  • url

    • 用于绘制的图像文件的绝对 URL。可以是任何支持的文件格式。对于绘制水印或非矩形叠加,Cloudflare 建议使用 PNG 或 WebP 图像。
  • widthheight

    • 叠加图像的最大尺寸。接受整数(像素)或 01 之间的小数,表示原始图像尺寸的分数。例如,height: 0.25 将叠加高度设置为父图像高度的 25%。
  • fitgravity

    • 影响 widthheight 的解释。与主图像相同。
  • opacity

    • 0(透明)到 1(不透明)之间的浮点数。例如,opacity: 0.5 使叠加半透明。
  • repeat

    • 如果设置为 true,叠加图像将平铺以覆盖整个区域。这适用于类似库存照片的水印。
    • 如果设置为 "x",叠加图像将仅水平平铺(形成一行)。
    • 如果设置为 "y",叠加图像将仅垂直平铺(形成一列)。
  • topleftbottomright

    • 叠加图像相对于给定边缘的位置。每个属性是以像素为单位的偏移量。0 与边缘精确对齐。例如,left: 10 将叠加的左侧定位在绘制它的图像左边缘向内 10 像素处。bottom: 0 将叠加的底部与背景图像的底部对齐。

      同时设置 leftright,或同时设置 topbottom 是错误。

      如果未指定位置,图像将居中。

  • background

    • 在叠加图像下方添加的背景色。与主图像相同。
  • rotate

    • 旋转叠加图像的度数。与主图像相同。

使用 Images 绑定绘制

通过绑定与 Images 交互 时,Images API 支持 .draw() 方法。

叠加图像接受的选项为 opacityrepeattopleftbottomright

// Fetch image and watermark
const img = await fetch("https://example.com/image.png");
const watermark = await fetch("https://example.com/watermark.png");

const response = (
	await env.IMAGES.input(img.body)
		.transform({ width: 1024 })
		.draw(watermark.body, { opacity: 0.25, repeat: true })
		.output({ format: "image/avif" })
).response();

return response;

要对叠加图像应用参数,可以在 .draw() 请求内传递子 .transform() 函数。

在以下示例中,水印在绘制到基础图像上之前使用 rotatewidth 进行处理,并使用 opacityrotate 选项。

// Fetch image and watermark
const response = (
	await env.IMAGES.input(img.body)
		.transform({ width: 1024 })
		.draw(watermark.body, { opacity: 0.25, repeat: true })
		.output({ format: "image/avif" })
).response();

示例

库存照片水印

image: {
  draw: [
    {
      url: 'https://example.com/watermark.png',
      repeat: true, // Tiled over entire image
      opacity: 0.2, // and subtly blended
    },
  ],
}

签名

image: {
  draw: [
    {
      url: 'https://example.com/by-me.png', // Predefined logo/signature
      bottom: 5, // Positioned near bottom right corner
      right: 5,
    },
  ],
}

居中图标

image: {
  draw: [
    {
      url: 'https://example.com/play-button.png',
      // Center position is the default
    },
  ],
}

组合

可以在一张图像中组合多个操作:

image: {
  draw: [
    { url: 'https://example.com/watermark.png', repeat: true, opacity: 0.2 },
    { url: 'https://example.com/play-button.png' },
    { url: 'https://example.com/by-me.png', bottom: 5, right: 5 },
  ],
}

这篇文档对您有帮助吗?