2
votes

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.

1
There are many solutions to this but you can try sf = max(100 / pic_w, 100 / pic_h) for starters - Selcuk
What GUI toolkit are you using? If you're doing what I think you're doing, and this is in Tk, canvas.create_rectangle is going to create a live object for each pixel, which is going to be very, very slow and memory hungry. Try using libraries like PIL or ImageMagick for your image operations, to create a single Bitmap object that can be blitted efficiently. - Lie Ryan
yes that is true it is in tkinter, i realize this is incredibly slow but it is part of a school based challenge therefore ^ good idea but the challenge has criteria :D - Tom Cupis

1 Answers

1
votes
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)