Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I properly set DPI when saving a pillow image?

I am trying to create images programatically on Python using Pillow library but I'm having problems with the image quality of the text inside the image.

I want to save the Image the I generate to PNG, so I'm setting the DPI when saving according to this, but whether I save with dpi=(72,72) or dpi=(600,600) it visually looks the same.

My code for doing it is the following:

from PIL import Image, ImageDraw, ImageFont

def generate_empty_canvas(width, height, color='white'):
    size = (width, height)
    return Image.new('RGB', size, color=color)

def draw_text(text, canvas):
    font = ImageFont.truetype('Verdana.ttf', 10)
    draw = ImageDraw.Draw(canvas)
    if '\n' not in text:
        draw.text((0, 0), text, font=font, fill='black')
    else:
        draw.multiline_text((0, 0), text, font=font, fill='black')

def create_sample():
    text = 'aaaaaaaaaaaaaaaaaa\nbbbbbbbbbbbbbbbbbbbbbbb\nccccccccccccccccccccc'
    canvas = generate_empty_canvas(200, 50)
    draw_text(text, canvas)
    canvas.save('low_quality.png', dpi=(72, 72))
    canvas.save('high_quality.png', dpi=(600, 600))

The low_quality.png is:

Image dpi=72

The high_quality.png is:

Image dpi=600

As it's visible by the images the quality didn't change. What am I doing wrong here?

Where do I set the DPI so that the image really has dpi=600?

like image 682
lucasamaral Avatar asked Jul 10 '15 22:07

lucasamaral


1 Answers

The DPI values are only metadata on computer images. They give hints on how to display or print an image.

Printing a 360×360 image with 360 dpi will result in a 1×1 inches printout.

A simplified way to explain it: The DPI setting recommends a zoom level for the image.

Saving with other DPIs will not change the content of the image. If you want a larger image create a larger canvas and use a larger font.

like image 166
Klaus D. Avatar answered Oct 11 '22 05:10

Klaus D.