I am trying to dynamically increase image size with respect to font and text given to draw.text()
.
Orignal Problem is to create signature image based on name and the font user selects.
Here is my code
from PIL import (Image, ImageDraw, ImageFont,)
width=20
height=20
selected_font='simply_glomrous.ttf'
font_size=30
img = Image.new('RGBA', (width, height), (255, 255, 255, 0))
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(selected_font, font_size)
draw.text((0,0), "Adil Malik", (0,0,0), font)
img.save('signature.png')
But i am still having same image size defined in width and height. Can we do dynamically resizing of image based on font and its size ?
Note: This question is opposite to this stackoverflow question
You can think about it this way. Image.filter() is the method to apply filters to images in PIL. And inside the parenthesis we will use ImageFilter library. This may seem a bit awkward but separating the filters and the method to apply them: .filter() can be helpful to understand it better.
Inside the parenthesis you can write the full path but if you just type a name, it will still save to a default folder, typically your c://Users/Name folder. ImageDraw in PIL (pillow) works similar to ImageFilter and ImageEnhance. First you create a drawing object with the image you’d like to work on and then apply it. Look below:
Though it may seem unusual to you, the Pillow library is imported using import PIL. 2. Import the module 3. Select and open the Image Now we need to pass the image, which we want to resize in the Image.open object of the PIL module.
If you’d like to save an image just apply .save() method instead of .show(). Inside the parenthesis you can write the full path but if you just type a name, it will still save to a default folder, typically your c://Users/Name folder. ImageDraw in PIL (pillow) works similar to ImageFilter and ImageEnhance.
Unfortunately, No one able to answer my question.
Basically, You can't set fix width and height while setting the font size. Both are dependent on each other. So if one increase, second one also increases.
So I have come up with another solution. I am just setting the font size and then based on that font size, I am setting width and height.
from PIL import (Image, ImageDraw, ImageFont,)
name = 'Adil Malik'
selected_font='simply_glomrous.ttf'
font_size=30
font = ImageFont.truetype(selected_font, font_size)
font_size = font.getsize(name)
img = Image.new('RGBA', (font_size[0], font_size[0]), (255, 255, 255, 0))
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(selected_font, font_size)
draw.text((0,0), name, (0,0,0), font)
img.save('signature.png')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With