使用 Python(pillow) 剪切透明背景

Cut transparent background using Python(pillow)

我使用python模块html2image将html转换为图片,但是由于图片大小固定,html被破坏或截断并且有一个空白space。有什么方法可以使用 Python 来解决这个问题吗? (我使用聊天导出器生成 html 代码)

@commands.command("savemsg")
    async def savemsg(self, ctx, msgid, *, add_css=None):
        msglist = await ctx.channel.fetch_message(msgid)
        transcript = await chat_exporter.raw_export(ctx.channel, [msglist], "Asia/Seoul")

        if transcript is None:
            return

        f = open("savemsg.html", 'wb')
        f.write(transcript.encode())
        f.close()
        with open('savemsg.html') as f:
            hti.screenshot(html_str=f.read(), save_as='output.png', css_str=add_css)
        await ctx.send(content="Output", file=discord.File("output.png"))

Return https://cdn.discordapp.com/attachments/833899986805719040/846029096584216626/outr.png

这是使用 Python 裁剪非透明区域的一种方法:

  • 读取输入图像,并将其转换为 NumPy 数组。
    该阵列有 4 个颜色通道,第 4 个通道是 alpha(透明通道)。
  • 查找非透明像素的索引 - alpha 通道值大于零的索引。
  • 获取两个轴(左上角和右下角)的最小和最大索引。
  • 裁剪矩形(并将裁剪的矩形转换为图像)。
  • 保存裁剪后的图像(使用 RGBA 颜色格式)。

代码如下:

import numpy as np
from PIL import Image

# Read input image, and convert to NumPy array. 
img = np.array(Image.open('outr.png'))  # img is 1080 rows by 1920 cols and 4 color channels, the 4'th channel is alpha.

# Find indices of non-transparent pixels (indices where alpha channel value is above zero).
idx = np.where(img[:, :, 3] > 0)

# Get minimum and maximum index in both axes (top left corner and bottom right corner)
x0, y0, x1, y1 = idx[1].min(), idx[0].min(), idx[1].max(), idx[0].max()

# Crop rectangle and convert to Image
out = Image.fromarray(img[y0:y1+1, x0:x1+1, :])

# Save the result (RGBA color format).
out.save('inner.png')

结果:


抱歉忽略了 HTML 标签...
我希望你真的想问“如何使用 Python 切割非透明背景的区域”(而且你不打算使用 html2image 解决它 模块)。