Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to draw text to bitmap in python?

Tags:

python

bmp

I want to create text to bitmap. the text is considered long string text.

so please tell me how to create a bitmap from a text.

I tried this :

from PIL import Image, ImageFont
img = Image.new('L', (500, 500), color=0)
img_w, img_h = img.size
font = ImageFont.truetype('arial.ttf', 20)
mask = font.getmask('some text related location that is going to write here.'
                    'this is watermark text', mode='L')
mask_w, mask_h = mask.size
print(mask_w,mask_h)
print(type(mask))
d = Image.core.draw(img.im, 0)
# d = d.rotate(40)
d.draw_bitmap(((img_w - mask_w)/2, (img_h - mask_h)/2), mask, 255)
img = img.rotate(40)
img.show()
img.save('op.jpg')

But text is cut from both side. here is what i get. enter image description here

like image 223
Jessica Avatar asked Sep 03 '25 15:09

Jessica


1 Answers

The text is cut from both sides because it was already cut by the horizontal boundary of the image before you rotate it. You should create an image with a width large enough to accommodate the entire text before you rotate it. That is to say, you should create an Image object with a width of mask_w after you obtain it.

like image 62
blhsing Avatar answered Sep 05 '25 14:09

blhsing