Skip to main content
 首页 » 编程设计

python 魔杖 : composite image with transparency

2024年10月25日22lovecherry

我正在尝试使用 Wand 合成两张图像。计划是将图像 B 放在 A 的右侧,并使 B 的透明度为 60%。使用 IM 可以这样做:

composite -blend 60 -geometry +1000+0 b.jpg a.jpg new.jpg 

但是对于 Wand,我只能通过 composite() 方法看到以下内容:operator, left, top, width, height, image。

Wand 有可能吗?

请您参考如下方法:

要并排完成-geometry +1000+0,您可以将图像并排合成到新图像上。对于这个例子,我使用 Image.composite_channel对于一切。

with Image(filename='rose:') as A: 
    with Image(filename='rose:') as B: 
        B.negate() 
        with Image(width=A.width+B.width, height=A.height) as img: 
            img.composite_channel('default_channels', A, 'over', 0, 0 ) 
            img.composite_channel('default_channels', B, 'blend', B.width, 0 ) 

请注意,复合运算符在上面的示例中并没有产生太大影响。

要达到 -blend 60%,您需要创建一个 60% 的新 alpha channel ,并将其“复制”到源不透明度 channel 。

我将创建一个辅助函数来说明此技术。

def alpha_at_60(img): 
    with Image(width=img.width, 
               height=img.height, 
               background=Color("gray60")) as alpha: 
        img.composite_channel('default_channels', alpha, 'copy_opacity', 0, 0) 
 
with Image(filename='rose:') as A: 
    with Image(filename='rose:') as B: 
        B.negate() 
        with Image(width=A.width+B.width, height=A.height) as img: 
            img.composite_channel('default_channels', A, 'over', 0, 0 ) 
            alpha_at_60(B) #  Drop opacity to 60% 
            img.composite_channel('default_channels', B, 'blend', B.width, 0 )