首页 > 解决方案 > 使用 PIL 旋转 RGBA 图像后失去颜色

问题描述

我正在尝试使用 PIL 旋转 RGBA 图像,这就是图像的样子:

RGBA 图像

但是在旋转之后,它在 alpha = 0 处丢失了所有 RGB 值。

旋转

我已经为 rotate() 函数尝试了所有其他重采样类型,但它们甚至使事情变得更糟。

这是原始图像:http ://djosix.com/cell.png

标签: pythonimage-processingpython-imaging-library

解决方案


简短的回答:

alpha = image.split()[-1]
image = image.convert('RGB').rotate(angle)
image.putalpha(alpha.rotate(angle))

参考源代码:

https://github.com/python-pillow/Pillow/blob/master/src/PIL/Image.py#L2324

transform()中,由 调用rotate()

if self.mode == "RGBA":
    return (
        self.convert("RGBa")
        .transform(size, method, data, resample, fill, fillcolor)
        .convert("RGBA")
    )

转换为 RGBa 将根据这部分将 RGB 与 Alpha 相乘:

https://github.com/python-pillow/Pillow/blob/master/src/libImaging/Convert.c#L489

static void
rgbA2rgba(UINT8* out, const UINT8* in, int xsize)
{
    int x;
    unsigned int alpha, tmp;
    for (x = 0; x < xsize; x++) {
        alpha = in[3];
        *out++ = MULDIV255(*in++, alpha, tmp);
        *out++ = MULDIV255(*in++, alpha, tmp);
        *out++ = MULDIV255(*in++, alpha, tmp);
        *out++ = *in++;
    }
}

推荐阅读