'PyGame - Getting the size of a loaded image

Hello, even though you might think there was a similar question, mine is pretty different than this.

I am trying to load an image from a directory, and set my screen size (automatically) to the size of the image being loaded as "background".

import pygame
import sys
from pygame.locals import *

image_resources = "C:/Users/user/Desktop/Pygame App/image_resources/"

class load:
    def image(self, image):
        self.image = image
        return (image_resources + image)
    def texture(self, texture):
        self.texture = texture
        return (image_resources + texture)

bg = load().image("bg_solid_black.jpg")

pygame.init()

#screen = pygame.display.set_mode((width,height),0,32)

#background = pygame.image.load(bg).convert()

#width = background.get_width()
#height = background.get_height()

The image that I loaded with my "load()" class is set to the variable "bg" and I want to use the size of whatever I load as "bg" to determine the size of the window. If you try to move

background = pygame.image.load(bg).convert()

width = background.get_width()
height = background.get_height()

On top of this:

screen = pygame.display.set_mode((width,height),0,32)

PyGame returns an error, in which it states that the display mode is not set. If I do it like this:

screen = pygame.display.set_mode((width,height),0,32)

background = pygame.image.load(bg).convert()

width = background.get_width()
height = background.get_height()

of course, this is not true, since variables "width" and "height" are not defined for the use of "pygame.display.set_mode()".

I can not seem to figure this out, I though of solving through an OO manner, but I just can not seem to figure it out. Any help?

Thanks :)



Solution 1:[1]

The code I use is this:

import pygame
import os
import random


WIDTH = 750
HEIGHT = 600
WIN = pygame.display.set_mode((WIDTH, HEIGHT))

#Image Load
BG = pygame.image.load(os.path.join("assets", "background_space.png"))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Paora