python - 使用 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
解决方案
这是使用 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 模块来解决它)。
推荐阅读
- spring - 在春季批处理写入器中写入多个不相关的表
- android - Flutter 社交分享插件(facebook / instagram)不起作用
- ruby-on-rails - 使用未确认的帐户登录时,覆盖设计会话控制器以触发“确认您的电子邮件”电子邮件
- c - 如何在不影响性能的情况下实现原始类型的类型安全?
- reactjs - 制作 Service Worker 后,我的网站仅在我删除缓存时加载
- android - 如何在android的firebase recyclerview中播放和暂停音频
- angular - Angular 中的 @SkipSelf 装饰器是什么?
- javascript - 如何使用正则表达式删除字符串 Handlerbar.js 中的 HTML 标记
- reactjs - 防止函数在 React 中被重复调用
- html - 我的键盘快捷键无法保存(VS 代码)