Using Python and PIL, I summarized how to output an image with the character string drawn from the character string. I just prepare a background image and draw characters.
PIL PIL (Python Image Library) is a Python image processing library. It seems that development has stopped now, so it would be better to use the successor Pillow, but Anaconda has PIL installed as standard, and it was possible to realize with the PIL function. Therefore, PIL is used.
I couldn't find a page with the title of converting a character string to an image, so I used it after investigating how to draw characters while looking at how to use the image processing library. In the first place, I don't think there is a demand for converting character strings to images, but I think there are small uses such as converting email addresses to images as a measure against spam. Therefore, the title was "Converting a character string to an image".
In the work, I referred to How to use Python's image processing library Pillow (PIL).
After creating an Image object with PIL.Image.new ()
, create a Draw object with PIL.ImageDraw.Draw ()
. In PIL.Image.new ()
, the color mode, image size, and background color are specified as arguments.
Specify the font used in PIL.ImageFont.truetype
and its size. After that, I got the size (number of pixels) of the text to be drawn with draw.textsize ()
, adjusted the text so that it was in the desired place, and drew it with draw.text ()
.
import PIL.Image
import PIL.ImageDraw
import PIL.ImageFont
#Settings for font, size, and text to draw
ttfontname = "C:\\Windows\\Fonts\\meiryob.ttc"
fontsize = 36
text = "Implicit type declaration"
#Set image size, background color, font color
canvasSize = (300, 150)
backgroundRGB = (255, 255, 255)
textRGB = (0, 0, 0)
#Creating an image to draw characters
img = PIL.Image.new('RGB', canvasSize, backgroundRGB)
draw = PIL.ImageDraw.Draw(img)
#Draw a character string on the prepared image
font = PIL.ImageFont.truetype(ttfontname, fontsize)
textWidth, textHeight = draw.textsize(text,font=font)
textTopLeft = (canvasSize[0]//6, canvasSize[1]//2-textHeight//2) #1 from the front/6, placed in the center of the top and bottom
draw.text(textTopLeft, text, fill=textRGB, font=font)
img.save("image.png ")
The image was output safely.
Recommended Posts