I have a list of PNGs that are 120px by 80px each. But my character in the PNG is really smaller, only occupying the middle. Is there a way to loop through all the elements and make it so that the border of these PNGs exactly fit the image? Kind of like a really tight picture frame.
CodePudding user response:
I'll assume that the list actually contains pygame.Surface
s, so what you can do is use pygame.Surface.get_bounding_rect
to get the smallest rectangle required to fit all the data and then subsurface all the surfaces in that list, so basically you'd have this:
image_list = [...]
image_list = [image.subsurface(image.get_bounding_rect()) for image in image_list]
CodePudding user response:
If you have all the images in one folder, you can use the PIL library to crop it.
from PIL import image
def crop_center(pil_img, crop_width, crop_height):
img_width, img_height = pil_img.size
return pil_img.crop(((img_width - crop_width) // 2,
(img_height - crop_height) // 2,
(img_width crop_width) // 2,
(img_height crop_height) // 2))
new = crop_center(image, h1, h2) # replace h1 and h2 with the dimensions you need your image to be.
im_new.save('your image path', quality=x) # replace your image path with the path of your files
#replace x with what you want your image quality to be
If you need to resize it, that is also possible using the PIL library:
from PIL import image
image = Image.open('image.jpg')
image2 = image.resize((x,y)) # replace x and y with your dimensions you need
image2.save('resized.jpg') # saving the resized image.