UltraLuminous UltraLuminous - 1 month ago 8
Python Question

Python - getting image size with function returns error

I am quite new to python and I was trying to get the height of an image using a function copied from another post, so that I can correctly position the image in the window for a game I am making with PyGame. Any ideas?

Code:

http://pastebin.com/atZ6vbZQ
(get_image_size copied from here)

Error:

Traceback (most recent call last):
File "Game/game.py", line 67, in
displayCar((display_width / 2), (display_height - (get_image_size(Lightning).height)))
File "Game/game.py", line 22, in get_image_size
with open(fname, 'rb') as fhandle:
TypeError: coercing to Unicode: need string or buffer, pygame.Surface found

Answer

get_image_size(fname) expects file name but you use Lightning which is pygame.Surface() object


But pygame.Surface() is very useful you can get its size (and position) as pygame.Rect() object

Lightning_rect = Lightning.get_rect()

and then you have image size and position

Lightning_rect.width
Lightning_rect.height
Lightning_rect.x
Lightning_rect.y
Lightning_rect.left
Lightning_rect.right
Lightning_rect.top
Lightning_rect.bottom

Lightning_rect.center 

etc.

You can change position using

Lightning_rect.x = new_x
Lightning_rect.y = new_y

or

Lightning_rect.topleft = (new_x, new_y)

And draw/blit

gameDisplay.blit(Lightning, Lightning_rect)

if you want to center image on screen then

gameDisplay_rect = gameDisplay.get_rect()

Lightning_rect.center = gameDisplay_rect.center

BWT: you can use Rect() to check collision with another Rect() (pygame.Rect.colliderect) or point (pygame.Rect.collidepoint) - ie. with mouse position to build button.