Sergei Basharov
Sergei Basharov

Reputation: 53920

Programmatically change image resolution

I have calculated that if I want my generated image to be A4 size @ 600dpi for print purpose, it needs to be 7016x4961px @ 72dpi. So, I generate it programmatically, then test it in Photoshop and it seems to be fine so if I resize it, it gets proper size and resolution

Image size dialog in Photoshop.

What I wonder about is if it's possible to make this resizing programmatically, preferably with PIL, but not necessarily with it. I need to make it higher DPI.

Upvotes: 23

Views: 109812

Answers (3)

python-noob
python-noob

Reputation: 21

Here's how you can resize by batch (per folder) and skip other file types and Mac system files like .DS_Store

from PIL import Image
import os

Image.MAX_IMAGE_PIXELS = None

path = "./*your-source-folder*"

resize_ratio = 2  # where 0.5 is half size, 2 is double size



def resize_aspect_fit():
    dirs = os.listdir(path)
    for item in dirs:
        print(item)
        if item == '.DS_Store':
            continue

        if item == 'Icon\r':
            continue
      
        if item.endswith(".mp4"):
            continue
        
        if item.endswith(".txt"):
            continue
        
        if item.endswith(".db"):
            continue

        if os.path.isfile(path+item):
            image = Image.open(path+item)
            file_path, extension = os.path.splitext(path+item)
            new_image_height = int(image.size[0] / (1/resize_ratio))
            new_image_length = int(image.size[1] / (1/resize_ratio))

            image = image.resize((new_image_height, new_image_length), Image.ANTIALIAS)
            
            image.save("./*your-output-folder*/" + item)


resize_aspect_fit()

Upvotes: 0

MatthieuW
MatthieuW

Reputation: 2372

If you have generated your image 7016 x 4961 px, it is already A4 at 600 dpi. So you don't need to resize it, you just have to set resolution information in file.

You can do it with PIL:

from PIL import Image

im = Image.open("test.png")
im.save("test-600.png", dpi=(600,600))

Upvotes: 39

Chewie
Chewie

Reputation: 7235

This code will resize a PNG image into 7016x4961 with PIL:

size = 7016, 4961
im = Image.open("my_image.png")
im_resized = im.resize(size, Image.ANTIALIAS)
im_resized.save("my_image_resized.png", "PNG")

Perhaps a better approach would be to make your canvas x times bigger prior to printing, where x is a factor you have to figure out (7016x4961 in size for this particular image).

Upvotes: 24

Related Questions