使用 Python 在演示文稿中管理图像变换效果

概述

Aspose.Slides 将图片调整表示为有序的图像变换操作集合。对于图片框,首先获取框的 Picture 并访问 Picture.getImageTransform。返回的 ImageTransformOperationCollection 允许您追加、枚举、检查、删除以及清除效果,而无需重新写入原始图像字节。

本文演示了亮度和对比度、颜色变换、模糊、透明度、有序效果链、有效值、删除以及 PPTX 循环验证的完整工作流程。

了解效果所有权和图像复用

图像资源与显示该图像的图片是不同的对象:

  • PPImage 存储或引用演示文稿拥有的源图像数据。
  • Picture 属于图片填充并引用图像资源,同时存储图像变换集合。
  • PictureFrame 是拥有相应图片填充、几何形状、裁剪设置以及其他框级格式的幻灯片形状。

因此,图像变换操作不会修改 PPImage 中的字节。当相同的 PPImage 多次传递给 ShapeCollection.addPictureFrame 时,每个新的图片框都会获得自己的 Picture 和自己的变换集合。对一个框应用灰度不会使其他框也变成灰度,即使它们复用了相同的嵌入图像资源。

相同的 Picture.getImageTransform 模型也被其他图片填充使用,例如形状或幻灯片背景。下面的示例侧重于图片框。

使用有效的参数范围和单位

演示的方法使用以下语义范围和单位。即使特定库版本不会立即拒绝所有超出范围的值,也请保持在这些范围内;目标演示文稿格式可能在保存或 PowerPoint 打开文件时对无效数据进行标准化、省略或拒绝。

操作 参数 有效范围和单位
addBrightnessContrastEffect brightness, contrast -100 到 100,百分比;0 保持组件不变。
addGrayScaleEffect None 无数值参数。Alpha 保持不变。
addDuotoneEffect color1, color2 用于暗像素和亮像素的两种颜色。java.awt.Color 中的 RGB 和 alpha 通道使用 0 到 255。
addTintEffect hue, amount 色相范围为包含 0 到不含 360 的度数;amount 为 -100 到 100,百分比。
addHSLEffect hue, saturation, luminance 色相范围为包含 0 到不含 360 的度数;饱和度和亮度为 -100 到 100,百分比。
addColorReplaceEffect color 替换颜色使用 0 到 255 的通道值。现有的 alpha 值保持不变。
addBlurEffect radius, grow 半径为非负,以点为单位;grow 为布尔值,控制模糊内容是否可以超出原始边界。
addAlphaModulateFixedEffect amount 非负百分比。使用 0 到 100 进行普通不透明度缩放:0 为完全透明,100 保留现有 alpha。
addAlphaReplaceEffect alpha 0 到 100,百分比不透明度。
addAlphaBiLevelEffect threshold 0 到 100,百分比 alpha 阈值。低于阈值的像素变为透明,阈值及以上的像素变为不透明。

对于固定 alpha 调制,透明度和不透明度是互补的。例如,35% 透明度对应 65% 的 alpha 调制量。

应用亮度和对比度

ImageTransformOperationCollection.addBrightnessContrastEffect 返回一个 BrightnessContrast 操作。其标量设置在创建操作时提供。BrightnessContrast.getEffective 返回计算后只读的值,可用于检查或记录。

以下示例将亮度提高 15%,对比度提高 20%,然后渲染预览而不修改嵌入的图像:

import jpype
import asposeslides
from pathlib import Path

if not jpype.isJVMStarted():
    jpype.startJVM()

from asposeslides.api import ImageFormat, Presentation, ShapeType

presentation = Presentation()
try:
    slide = presentation.getSlides().get_Item(0)

    image_data = Path("photo.png").read_bytes()
    image_bytes = jpype.JArray(jpype.JByte)(image_data)
    image = presentation.getImages().addImage(image_bytes)
    picture_frame = slide.getShapes().addPictureFrame(ShapeType.Rectangle, 50, 50, 400, 260, image)

    image_transform = picture_frame.getPictureFormat().getPicture().getImageTransform()
    brightness_contrast = image_transform.addBrightnessContrastEffect(15.0, 20.0)

    effective_values = brightness_contrast.getEffective()
    print("Brightness: ", effective_values.getBrightness(), "%", sep="")
    print("Contrast: ", effective_values.getContrast(), "%", sep="")

    preview = slide.getImage()
    try:
        preview.save("brightness-contrast-preview.png", ImageFormat.Png)
    finally:
        preview.dispose()
finally:
    presentation.dispose()

BrightnessContrast 是 Office 2010 图片效果扩展,比标准 DrawingML 亮度效果的可移植性差。当亮度和对比度在 PPTX 循环后必须保持可编辑时,请使用 ImageTransformOperationCollection.addLuminanceEffect 并在重新打开文件后验证结果。格式限制章节更详细地解释了此区别。

应用颜色变换

颜色效果可以独立应用于复用同一图像资源的不同图片框。以下示例创建五个框,并分别应用灰度、双音、色调、HSL 调整和颜色替换。

Duotone 包含两个可独立编辑的颜色参数:color1 映射暗像素,color2 映射亮像素。这使其成为一个设置比单一标量更复杂的效果示例。

import jpype
import asposeslides
from pathlib import Path

if not jpype.isJVMStarted():
    jpype.startJVM()

from asposeslides.api import Presentation, SaveFormat, ShapeType
from java.awt import Color

presentation = Presentation()
try:
    slide = presentation.getSlides().get_Item(0)

    image_data = Path("photo.png").read_bytes()
    image_bytes = jpype.JArray(jpype.JByte)(image_data)
    image = presentation.getImages().addImage(image_bytes)

    gray_frame = slide.getShapes().addPictureFrame(ShapeType.Rectangle, 20, 20, 180, 120, image)
    gray_frame.getPictureFormat().getPicture().getImageTransform().addGrayScaleEffect()

    duotone_frame = slide.getShapes().addPictureFrame(ShapeType.Rectangle, 220, 20, 180, 120, image)
    duotone = duotone_frame.getPictureFormat().getPicture().getImageTransform().addDuotoneEffect()
    duotone.getColor1().setColor(Color(0, 0, 128))
    duotone.getColor2().setColor(Color(255, 215, 0))

    tint_frame = slide.getShapes().addPictureFrame(ShapeType.Rectangle, 420, 20, 180, 120, image)
    tint_frame.getPictureFormat().getPicture().getImageTransform().addTintEffect(210.0, 35.0)

    hsl_frame = slide.getShapes().addPictureFrame(ShapeType.Rectangle, 120, 170, 180, 120, image)
    hsl_frame.getPictureFormat().getPicture().getImageTransform().addHSLEffect(30.0, 20.0, -10.0)

    replacement_frame = slide.getShapes().addPictureFrame(ShapeType.Rectangle, 320, 170, 180, 120, image)
    color_replacement = replacement_frame.getPictureFormat().getPicture().getImageTransform().addColorReplaceEffect()
    color_replacement.getColor().setColor(Color(100, 149, 237))

    presentation.save("color-transformations.pptx", SaveFormat.Pptx)
finally:
    presentation.dispose()

addColorReplaceEffect 将每个像素的颜色替换为固定颜色,同时保留 alpha。它不同于 addColorChangeEffect,后者将一种源颜色映射到另一种,并暴露源和目标颜色格式。

应用亮度阈值

亮度阈值可以使扫描页上的淡淡标记更容易与背景区分。addGrayScaleEffect 保留中间的灰度色阶。addBiLevelEffect 将亮度映射为黑或白,而 addAlphaBiLevelEffect 对不透明度应用阈值。

亮度阈值范围为 0% 到 100%,含边界。低于阈值的像素变为黑色,阈值及以上的像素变为白色。提高阈值会使更多色阶变黑,因为它们落在阈值以下。

下载 grayscale-swatches.png 到工作目录。每个标签给出原始灰度在 0 至 255 的比例。示例将原始图像放在两份副本旁边,并在演示文稿中保存每份副本的阈值。

import jpype
import asposeslides
from pathlib import Path

if not jpype.isJVMStarted():
    jpype.startJVM()

from asposeslides.api import Presentation, SaveFormat, ShapeType, SlideSizeScaleType

presentation = Presentation()
try:
    presentation.getSlideSize().setSize(720.0, 150.0, SlideSizeScaleType.DoNotScale)
    shapes = presentation.getSlides().get_Item(0).getShapes()

    image_data = Path("grayscale-swatches.png").read_bytes()
    image_bytes = jpype.JArray(jpype.JByte)(image_data)
    image = presentation.getImages().addImage(image_bytes)

    frames = []
    for index, caption in enumerate(("Original", "Threshold 20%", "Threshold 60%")):
        x = 12 + 240 * index
        label = shapes.addAutoShape(ShapeType.Rectangle, x, 12, 216, 36)
        label.getTextFrame().setText(caption)
        frame = shapes.addPictureFrame(ShapeType.Rectangle, x, 60, 216, 72, image)
        frames.append(frame)

    frames[1].getPictureFormat().getPicture().getImageTransform().addBiLevelEffect(20.0)
    frames[2].getPictureFormat().getPicture().getImageTransform().addBiLevelEffect(60.0)

    presentation.save("luminance-threshold.pptx", SaveFormat.Pptx)
finally:
    presentation.dispose()

在 PowerPoint 中打开输出的演示文稿以比较这三个框。标记为 96 的样本大约有 38% 的亮度(96/255)。在 20% 阈值时变为白色,在 60% 阈值时变为黑色。

原始灰度样本旁边的黑白结果,亮度阈值为 20% 和 60%

添加模糊、透明度和 Alpha 效果

addBlurEffect 影响所有颜色通道,包括 alpha。当模糊边缘可能超出原始图片边界时,将 grow 设置为 True。

要实现均匀透明度,请使用 addAlphaModulateFixedEffect。它将每个现有的 alpha 值相乘,使部分透明像素保持比例差异。addAlphaReplaceEffect 则为所有像素分配单一的 alpha 值。addAlphaBiLevelEffect 根据阈值将 alpha 转换为两个层级。

import jpime
import asposeslides
from pathlib import Path

if not jpime.isJVMStarted():
    jpime.startJVM()

from asposeslides.api import Presentation, SaveFormat, ShapeType

presentation = Presentation()
try:
    slide = presentation.getSlides().get_Item(0)

    image_data = Path("photo.png").read_bytes()
    image_bytes = jpime.JArray(jpime.JByte)(image_data)
    image = presentation.getImages().addImage(image_bytes)

    blurred_frame = slide.getShapes().addPictureFrame(ShapeType.Rectangle, 20, 20, 200, 140, image)
    blur = blurred_frame.getPictureFormat().getPicture().getImageTransform().addBlurEffect(4.5, True)
    blur.setRadius(5)

    transparent_frame = slide.getShapes().addPictureFrame(ShapeType.Rectangle, 240, 20, 200, 140, image)
    alpha_modulate = transparent_frame.getPictureFormat().getPicture().getImageTransform().addAlphaModulateFixedEffect(65.0)
    alpha_modulate.setAmount(60.0)

    uniform_alpha_frame = slide.getShapes().addPictureFrame(ShapeType.Rectangle, 20, 180, 200, 140, image)
    uniform_alpha_frame.getPictureFormat().getPicture().getImageTransform().addAlphaReplaceEffect(55.0)

    binary_alpha_frame = slide.getShapes().addPictureFrame(ShapeType.Rectangle, 240, 180, 200, 140, image)
    alpha_bi_level = binary_alpha_frame.getPictureFormat().getPicture().getImageTransform().addAlphaBiLevelEffect(50.0)
    alpha_bi_level.setThreshold(45.0)
    binary_alpha_frame.getPictureFormat().getPicture().getImageTransform().addAlphaInverseEffect()

    presentation.save("blur-and-alpha-effects.pptx", SaveFormat.Pptx)
finally:
    presentation.dispose()

其他无参数的 alpha 操作包括 addAlphaCeilingEffect,它使所有非零 alpha 完全不透明;addAlphaFloorEffect,它使所有低于 100% 的 alpha 完全透明;以及 addAlphaInverseEffect,它将 alpha 改为 100% - alpha。

构建有序效果链

每个 add...Effect 方法都会将新操作追加到集合的末尾。渲染器将集合视为有序管道:操作 0 的输出成为操作 1 的输入,依此类推。因此,顺序不同的相同操作会产生不同的图像。

例如,先灰度后色调会先去除色彩信息再对亮度结果重新着色。先色调后灰度会再次去除色调。同样,alpha 替换可以覆盖先前操作计算的 alpha 值,而 alpha 调制则保留其相对差异。

以下示例构建一个四操作链,将其保存为 PPTX,重新打开演示文稿,检查操作类型及其顺序,并渲染重新打开的结果:

import jpype
import asposeslides
from pathlib import Path

if not jpype.isJVMStarted():
    jpype.startJVM()

from asposeslides.api import AlphaModulateFixed, Blur, GrayScale, ImageFormat, PictureFrame, Presentation, SaveFormat, ShapeType, Tint

presentation = Presentation()
try:
    slide = presentation.getSlides().get_Item(0)
    image_data = Path("photo.png").read_bytes()
    image_bytes = jpype.JArray(jpype.JByte)(image_data)
    image = presentation.getImages().addImage(image_bytes)
    picture_frame = slide.getShapes().addPictureFrame(ShapeType.Rectangle, 50, 50, 400, 260, image)

    image_transform = picture_frame.getPictureFormat().getPicture().getImageTransform()
    image_transform.addGrayScaleEffect()
    image_transform.addTintEffect(220.0, 25.0)
    image_transform.addBlurEffect(2.5, False)
    image_transform.addAlphaModulateFixedEffect(80.0)

    presentation.save("image-transform-chain.pptx", SaveFormat.Pptx)
finally:
    presentation.dispose()

reopened_presentation = Presentation("image-transform-chain.pptx")
try:
    reopened_shape = reopened_presentation.getSlides().get_Item(0).getShapes().get_Item(0)

    if isinstance(reopened_shape, PictureFrame):
        reopened_transform = reopened_shape.getPictureFormat().getPicture().getImageTransform()
        expected_types = (GrayScale, Tint, Blur, AlphaModulateFixed)
        order_is_preserved = reopened_transform.size() == len(expected_types)
        for index, expected_type in enumerate(expected_types):
            order_is_preserved = order_is_preserved and isinstance(reopened_transform.get_Item(index), expected_type)
        print("The effect chain was preserved." if order_is_preserved else "The effect chain changed during the round trip.")

        rendered_slide = reopened_presentation.getSlides().get_Item(0).getImage()
        try:
            rendered_slide.save("reopened-effect-chain.png", ImageFormat.Png)
        finally:
            rendered_slide.dispose()
    else:
        print("The reopened shape is not a picture frame.")
finally:
    reopened_presentation.dispose()

该集合并未强制兼容性矩阵,将颜色、alpha 和模糊操作限制在不同链中。它们可以组合,但组合并不总是有用。固定颜色替换会移除早期颜色效果产生的 RGB 变化;双音后再进行灰度会去除两种选定颜色;alpha ceiling、floor、replace 或 bi-level 操作可以丢弃先前创建的 alpha 细节。应根据所需的像素处理顺序构建链,而不是将其视为无序的格式标志。

The same image passes through grayscale then tint, and tint then grayscale. The two final grayscale images have different tones.

In this illustrative Aspose.Slides for .NET 26.11 render, a 220° tint at 25% leaves the grayscale image unchanged. Applying the same tint before grayscale produces different tones.

检查可编辑和有效值

可编辑的操作是存储在 Picture.getImageTransform 中的对象。根据效果的不同,它可能直接暴露可写成员。例如,Blur 暴露可写的 radius 和 grow 值,AlphaModulateFixed 暴露可写的 amount,以及 AlphaBiLevel 暴露可写的 threshold。像 Duotone 这样的颜色效果暴露可变的 ColorFormat 对象。

某些操作类,包括 BrightnessContrast、HSL、Tint 和 AlphaReplace,不将其创建时的标量暴露为可写属性。要更改这些设置,需要删除该操作并在所需位置添加替代操作。

getEffective 返回的有效数据是计算后的只读值。它对于解析主题相关颜色和读取渲染器使用的标准化值很有帮助,但它不是另一个编辑界面。下面的示例枚举链并检查相应 API 提供的有效值:

import jpype
import asposeslides

if not jpype.isJVMStarted():
    jpype.startJVM()

from asposeslides.api import AlphaBiLevel, AlphaModulateFixed, AlphaReplace, Blur, BrightnessContrast, ColorReplace, Duotone, HSL, Luminance, PictureFrame, Presentation, Tint

presentation = Presentation("image-transform-chain.pptx")
try:
    picture_frame = None

    for shape in presentation.getSlides().get_Item(0).getShapes():
        if isinstance(shape, PictureFrame):
            picture_frame = shape
            break

    if picture_frame is not None:
        image_transform = picture_frame.getPictureFormat().getPicture().getImageTransform()

        for index in range(image_transform.size()):
            operation = image_transform.get_Item(index)
            print(index, ": ", operation.getClass().getSimpleName(), sep="")

            if isinstance(operation, BrightnessContrast):
                data = operation.getEffective()
                print("  Brightness: ", data.getBrightness(), sep="")
                print("  Contrast: ", data.getContrast(), sep="")
            elif isinstance(operation, Luminance):
                data = operation.getEffective()
                print("  Brightness: ", data.getBrightness(), sep="")
                print("  Contrast: ", data.getContrast(), sep="")
            elif isinstance(operation, Duotone):
                data = operation.getEffective()
                print("  Dark color: ", data.getColor1(), sep="")
                print("  Light color: ", data.getColor2(), sep="")
            elif isinstance(operation, ColorReplace):
                data = operation.getEffective()
                print("  Replacement color: ", data.getColor(), sep="")
            elif isinstance(operation, HSL):
                data = operation.getEffective()
                print("  HSL: ", data.getHue(), ", ", data.getSaturation(), ", ", data.getLuminance(), sep="")
            elif isinstance(operation, Tint):
                data = operation.getEffective()
                print("  Tint: ", data.getHue(), ", ", data.getAmount(), sep="")
            elif isinstance(operation, Blur):
                data = operation.getEffective()
                print("  Blur radius: ", data.getRadius(), " pt", sep="")
            elif isinstance(operation, AlphaModulateFixed):
                data = operation.getEffective()
                print("  Alpha amount: ", data.getAmount(), "%", sep="")
            elif isinstance(operation, AlphaReplace):
                data = operation.getEffective()
                print("  Replacement alpha: ", data.getAlpha(), "%", sep="")
            elif isinstance(operation, AlphaBiLevel):
                data = operation.getEffective()
                print("  Alpha threshold: ", data.getThreshold(), "%", sep="")
finally:
    presentation.dispose()

诸如灰度、alpha ceiling 和 alpha inverse 等无参数效果仍然拥有有效数据对象,但没有可打印的标量设置。它们的存在和在集合中的位置才是重要信息。

删除或清除图像变换

使用 ImageTransformOperationCollection.removeAt 按索引删除单个操作。由于删除后索引会移动,先搜索目标再在枚举后删除。使用 ImageTransformOperationCollection.clear 删除整个链。

import jpype
import asposeslides

if not jpype.isJVMStarted():
    jpype.startJVM()

from asposeslides.api import Blur, PictureFrame, Presentation, SaveFormat

presentation = Presentation("image-transform-chain.pptx")
try:
    picture_frame = None

    for shape in presentation.getSlides().get_Item(0).getShapes():
        if isinstance(shape, PictureFrame):
            picture_frame = shape
            break

    if picture_frame is not None:
        image_transform = picture_frame.getPictureFormat().getPicture().getImageTransform()
        blur_index = -1

        for index in range(image_transform.size()):
            if isinstance(image_transform.get_Item(index), Blur):
                blur_index = index
                break

        if blur_index >= 0:
            image_transform.removeAt(blur_index)
            print("The blur operation was removed.")

        image_transform.clear()
        print("Remaining operations: ", image_transform.size(), sep="")
        presentation.save("image-transforms-cleared.pptx", SaveFormat.Pptx)
finally:
    presentation.dispose()

删除或清除变换仅更改图片格式。它不会删除、重新压缩或以其他方式改变复用的 PPImage 资源。

考虑演示文稿格式和导出目标

图像变换源自 DrawingML,因此 PPTX 是效果链的首选可编辑格式。即使使用 PPTX,也并非每个操作都有相同的可移植性:

  • 标准 DrawingML 操作(如亮度、灰度、双音、色调、HSL、模糊以及常见的 alpha 操作)最有可能在 PPTX 循环后仍然存在。需要保存时,请始终重新打开生成的文件并检查集合。
  • BrightnessContrast 是 Office 2010 扩展,而非标准 DrawingML 亮度操作。它可用于内存渲染,但保存并重新打开 PPTX 后不一定保持为可编辑的 BrightnessContrast。请优先使用 addLuminanceEffect 以实现持久的亮度和对比度调整。
  • 二进制 PPT 格式早于完整的 DrawingML 效果模型。保存为 PPT 可能会省略不受支持的操作,将链缩减为受支持的子集,或近似外观。不要将 PPT 用作复杂可编辑链的验证格式。
  • 渲染为 PNG、JPEG、TIFF、PDF、SVG、HTML 或其他可视输出时,会将支持的链应用于渲染结果。这些输出不包含可编辑的 ImageTransformOperationCollection;光栅格式将结果展平为像素,文档/矢量导出则存储各自的渲染表示。
  • 效果并不会使链接的图像变为自包含。渲染链接图片仍然依赖于加载演示文稿时链接资源的可用性。

不同的演示文稿读取器在处理边缘情况时可能表现不同,尤其是当多种 alpha 或颜色量化操作组合时。对于关键输出,请使用生产环境中相同的 Aspose.Slides 版本同时测试可编辑的循环和最终导出格式。

常见问题

图像变换效果会修改嵌入的图像数据吗?

不会。操作属于图片填充使用的 Picture,底层的 PPImage 字节保持不变。

复用相同图像的两个图片框会共享它们的效果吗?

不会。复用 PPImage 可以避免重复的图像数据,但每个图片框通常拥有各自的 Picture 和图像变换集合。

可以组合颜色、模糊和 alpha 效果吗?

可以。集合接受它们在同一个有序链中。请考虑每个操作对前一个输出的影响,因为替换和阈值操作可能会丢弃之前的颜色或 alpha 细节。

为什么有效值是只读的?

有效数据代表用于渲染的计算值,包括解析后的颜色。请在变换集合中编辑可写成员的操作;否则请删除该操作并使用新创建参数添加替代操作。

应使用哪种格式来保留变换链?

使用 PPTX 并通过重新打开文件进行验证。旧版 PPT 无法完整表示 DrawingML 效果模型,渲染输出格式只保留外观而不保留可编辑的变换操作。