Search code examples
pythonimagealgorithmscaling

Python auto-scaling algorithm?


I have a problem with a simple image viewer i'm making. You see i would like have the picture the user selected to be up-scaled or down-scaled depending on the width and height of the picture. So a 1920 x 1080 pic will be reduced down to manageable size but a 40 x 40 picture will look big enough to see clearly.

This scale factor i'd preferably like in a single variable and without the use of IF statements because doing IF pic_h > 100: etc. ... you get the point.

Here is where i'm at:

for x in range(int(pic_w)):
    xline = target.readline()
    for y in range(int(pic_h)):
        pixel_data = xline[y:y+1]

        sf = <THIS IS THE BIT I NEED>
        y1b = (y*2)+0
        x1b = (x*2)+0
        y2b = (y*2)+2
        x2b = (x*2)+2

        y1w = (y*2)+0
        x1w = (x*2)+0
        y2w = (y*2)+2
        x2w = (x*2)+2

        if pixel_data == "1":
            pixel = canvas.create_rectangle(y1b, x1b, y2b, x2b, fill="black")
        elif pixel_data == "0":
            pixel = canvas.create_rectangle(y1b, x1b, y2b, x2b, fill="white")
        else:
            blah blah blah ............

The varibles pic_h and pic_w are the picture height and width.


Solution

  • width, height = maximum size in pixels
    x, y = number of pixels
    
    maxSize = min(width, height)
    width = = (maxSize//x)*x
    height = (maxSize//y)*y
    
    xScale = (width/x)
    yScale = (height/y)
    
    for row in xrange(y):
      for column in xrange(x):
        canvas.create_rectangle((column * xScale, row * yScale, (column * xScale)+xScale, (row * yScale)+yScale), fill=data)