Laura
Laura

Reputation: 1

how to make a reduced image file in python

I'm in a beginning programming class, and our project is to reduce an image to half it's size and then to double it's size.

How do I make a new picture that is the same picture as before, but with the reduced height and width?

This is the code that I have:

def main():
    originalPic=makePicture(pickAFile())
    show(originalPic)
    w=getWidth(originalPic)
    h=getHeight(originalPic)
    printNow(str(w)+ " \n" + str(h))
    if w % 2:
      reducedW=w/2
    else:
      reducedW=w/2+1  
    printNow(reducedW)
    if h % 2:
      reducedH=h/2
    else:
      reducedH=h/2+1
    printNow(reducedH)
    reducedPic=makePicture(reducedW, reducedH)
    show(reducedPic)

Upvotes: 0

Views: 83

Answers (2)

TigerhawkT3
TigerhawkT3

Reputation: 49318

Here's how I do that in PIL (Pillow):

from PIL import Image, ImageTk

my_image = Image.open('image.png') # open image
my_image = my_image.resize((my_image.size[0] * 2, my_image.size[1] * 2)) # resize
my_image.save('new_image.png') # save image
tk_image = ImageTk.PhotoImage(my_image) # convert for use in tkinter

Upvotes: 1

Malik Brahimi
Malik Brahimi

Reputation: 16711

As a beginner, you might want to stick to using Pygame rather than PIL to actually implement your skeleton code. We'll just load our image into Pygame, scale it up or down, and then save it.

import pygame, sys

pygame.init(); scale = 2 # or a half
image = pygame.image.load('image.png')

w = image.get_width() * scale 
h = image.get_height() * scale 

pygame.transform.scale(image, (w, h), image)
pygame.image.save(image, 'scaled_image.png')

Upvotes: 0

Related Questions