Back

Resize Image

Sript description

This script scales the image provided to a specific resolution. Below are two examples. The first is downscale and the second upscale

Result

Example Example
Example Example

Source Code

from PIL import Image
import math
im = Image.open("4by4colors.png")      #(input image)
pix = im.load()
print(im.size)


reqSizex = 1600 # required resolution x
reqSizey = 900 # required resolution y
newIm = Image.new('RGB', (reqSizex, reqSizey), color = 'black')
newpix = newIm.load() # all pixels


prevx = 0
prevy = 0
for y in range (0, reqSizey):
    for x in range (0, reqSizex):
        oldx = math.floor(x*im.size[0] / reqSizex)
        oldy = math.floor(y*im.size[1] / reqSizey)
        fracx = x*im.size[0] / reqSizex - oldx
        fracy = y*im.size[1] / reqSizey - oldy
        #if fracx == 0: fracx = 1
        #if fracy == 0: fracy = 1
        if oldx+1  < im.size[0]:
            #print(oldx, oldy, fracx)
            r = round(pix[oldx, oldy][0] * (1-fracx) + pix[oldx+1, oldy][0] * (fracx))
            g = round(pix[oldx, oldy][1] * (1-fracx) + pix[oldx+1, oldy][1] * (fracx))
            b = round(pix[oldx, oldy][2] * (1-fracx) + pix[oldx+1, oldy][2] * (fracx))
        else:
            r = round(pix[oldx, oldy][0])
            g = round(pix[oldx, oldy][1])
            b = round(pix[oldx, oldy][2])
        newpix[x,y] = (r,g,b)


        prevx = x
    prevy = y

newIm.save('4by4upscaled')  #
#print(newIm.size)