首页 > 解决方案 > 使用 Python(枕头)剪切透明背景

问题描述

我使用python模块html2image将html转换为图片,但是由于图片大小固定,html被打断或者截断,出现空白。有没有办法使用 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"))

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

标签: pythonhtmlimagediscordpython-imaging-library

解决方案


这是使用 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 模块来解决它)。


推荐阅读