在Python中将字符串转换为图像 [英] Convert string to image in python
问题描述
一周前,我开始学习python,希望编写一个小型程序将电子邮件转换为图像(.png),以便可以在论坛上共享它,而不必冒大量垃圾邮件的风险.
I started to learn python a week ago and want to write a small programm that converts a email to a image (.png) so that it can be shared on forums without risking to get lots of spam mails.
似乎python标准库没有包含可以执行此操作的模块,但是我发现它有一个PIL模块(PIL.ImageDraw).
It seems like the python standard libary doesn't contain a module that can do that but i`ve found out that there's a PIL module for it (PIL.ImageDraw).
我的问题是我似乎无法正常工作.
My problem is that i can't seem to get it working.
所以基本上我的问题是:
So basically my questions are:
- 如何在图像上绘制文本.
- 如何创建空白(白色)图像
- 有没有一种方法而无需实际创建文件,以便我可以在保存之前在GUI中显示它?
感谢您的帮助:)
当前代码:
import Image
import ImageDraw
import ImageFont
def getSize(txt, font):
testImg = Image.new('RGB', (1, 1))
testDraw = ImageDraw.Draw(testImg)
return testDraw.textsize(txt, font)
if __name__ == '__main__':
fontname = "Arial.ttf"
fontsize = 11
text = "example@gmail.com"
colorText = "black"
colorOutline = "red"
colorBackground = "white"
font = ImageFont.truetype(fontname, fontsize)
width, height = getSize(text, font)
img = Image.new('RGB', (width+4, height+4), colorBackground)
d = ImageDraw.Draw(img)
d.text((2, height/2), text, fill=colorText, font=font)
d.rectangle((0, 0, width+3, height+3), outline=colorOutline)
img.save("D:/image.png")
推荐答案
-
使用
ImageDraw.text
-但它不进行任何格式化,只在给定位置打印字符串
use
ImageDraw.text
- but it doesn't do any formating, it just prints string at the given location
img = Image.new('RGB', (200, 100))
d = ImageDraw.Draw(img)
d.text((20, 20), 'Hello', fill=(255, 0, 0))
找出文字大小:
text_width, text_height = d.textsize('Hello')
创建图像时,添加带有所需颜色(白色)的附加参数:
When creating image, add an aditional argument with the required color (white):
img = Image.new('RGB', (200, 100), (255, 255, 255))
,直到您使用Image.save
方法保存图像为止,将没有文件.然后,将其转换为GUI的格式进行显示只是适当的转换.这可以通过将图像编码到内存中的图像文件中来完成:
until you save the image with Image.save
method, there would be no file. Then it's only a matter of a proper transformation to put it into your GUI's format for display. This can be done by encoding the image into an in-memory image file:
import cStringIO
s = cStringIO.StringIO()
img.save(s, 'png')
in_memory_file = s.getvalue()
或者如果您使用python3:
or if you use python3:
import io
s = io.BytesIO()
img.save(s, 'png')
in_memory_file = s.getvalue()
然后可以将其发送到GUI.或者,您可以直接发送原始位图数据:
this can be then send to GUI. Or you can send direct raw bitmap data:
raw_img_data = img.tostring()
这篇关于在Python中将字符串转换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!