Variable issue in the setup() block

I load an img in my setup(). I can use its attributes like .width but when I attempt to use them as parameters to size(), I get NameError: global name ''img'' is not defined. But before that line, I’m happily referring to them in the print() statement.

def setup():
    global img
    img = loadImage("C:\\Users\foo\\code\\freq_plot\\image_experiment\\bal.jpg")
    
    #all these see the variable "img"
    one_pixel  = img.get(40,40)
    print(red(one_pixel), green(one_pixel), blue(one_pixel))
    print(type(img))
    print(img.height, img.width, )
    
    #size(img.height,img.width)   #NameError: global name 'img' is not defined'
    size(100,100)  # works fine
    
    noLoop()
    
def draw():
    print("done")

Welcome, @slashwreck!

You can use the settings() function:

def settings():
    img = loadImage('bal.jpg')
    size(img.width, img.height)
 
def setup():
    noLoop()
 
def draw():
    print('done')

Also, you can use a relative path for your image if you place the image file in the sketch folder (and avoid the whole "C:\\..." part).

2 Likes

Thanks. First I’ve heard of the settings() function. Don’t see it referenced in the reference. Am guessing it gets called automatically before setup()?

1 Like

It’s in the Java reference: https://processing.org/reference/settings_.html. I’ll open an issue on GitHub to add it to the Processing.py reference.

Edit: looks like somebody already did.

1 Like