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.
Asked
Active
Viewed 55 times
2 Answers
1
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]

Matiiss
- 5,970
- 2
- 12
- 29
-
Thank you so much! Now my character can move around without being blocked by "invisible blocks"! – AcastaTeacup Jul 27 '22 at 15:23
0
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.

tigerjade003
- 15
- 6
-
they are firstly using `pygame` and also they want to crop them to the bounding box size, the smallest rectangle that fits all the data in the image – Matiiss Jul 26 '22 at 22:44
-
@Matiis i'm confused on what you mean by that, they can use pygame stuff, then use one of the two method I mentioned above to resize/crop the image to whatever size they want. – tigerjade003 Jul 26 '22 at 22:48
-
that's not the only thing I mentioned, they said they want to crop it such that only the actual data is included in the resulting image, you can't just crop by some width or height like this, you need to get the bounding box, I think that PIL may actually provide such functionality – Matiiss Jul 26 '22 at 22:54