我在一个刚开始的编程类中,我们的项目是将图像缩小到其大小的一半,然后将其大小增加一倍。
我如何制作一张和以前一样的新照片,但高度和宽度都有所减少?
这是我的代码:
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)
以下是我如何在PIL(枕头)中做到这一点:
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
作为一名初学者,您可能希望坚持使用Pygame而不是PIL来实际实现您的骨架代码。我们只需将图像加载到Pygame中,放大或缩小,然后保存。
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')