I'm working on some python programming and I need some help as to how to double the size of a picture using the image module.... any ideas?!

12 Years
Discussion Span
Last Post by vegaseat

Is the picture you are loading smaller than what you want to display? If yes, the quality will suffer quite a bit! The program has to make up missing information.

Are you using the Python Image Library PIL for this?


I know the quality will be degraded, but I'm going for making it larger either way.... and yes I'm using the PIL.... and yes I am going from smaller to larger.....


Here is what I have done... some steps i did may not have been necessary, for example the extra color variables.... though now i need help with my zoom factor.... because this works for zooming in two times... but when higher numbers come about it skips pixels... i messed around with an extra for loop but its still the same... any other ideals?

def enlarge(oImage,w,h,x,y,zoom):
    nImage= EmptyImage(w*zoom,h*zoom)
    for q in range(w):
        x = x +zoom
        y = 0
        for z in range(h):
            color = oImage.getPixel(q,z)
            red= color[0]
            green= color[1]
            blue= color[2]
            nImage.setPixel(x ,y ,(red,green,blue))
            nImage.setPixel(x+1,y +1,(red,green,blue))
            nImage.setPixel(x+1, y,(red,green,blue))
            nImage.setPixel(x, y+1,(red,green,blue))
            for lea in range(1,zoom):
                nImage.setPixel(x, y+lea,(red,green,blue))
                nImage.setPixel(x+lea,y, (red, green,blue))
            y = y +zoom
    r = nImage
    winner = ImageWin("Big Picture", w*zoom, h*zoom)

def main():
    picname= raw_input("Enter Picture name with .jpg, .bmp, or ending: ")
    oImage= FileImage(picname)
    h= oImage.getHeight()
    w= oImage.getWidth()
    win = ImageWin("Original", w,h)
    y = 0
    zoom = input("Number of times to zoom: ")
    x = -(zoom)




I need to refraise what i said... I need help being able to take a user input for the number of times to zoom in and put it into my program but I need help with the for loop in how to do it.... pixels are being skipped when i go in to higher numbers!


I remember in school they talked about DIB (device indepentant bitmaps) to be best for stretching/enlarging. Was C class for graph artists.


Meh.... yea... I don't know what you are talking about ... but yea... I just need help looping it to the point where its not skipping Pixels......


Need to import image(not Image).... so on the top needs to be "from image import * "


Yes it is........... it is attached... just resave it as a .py file (which you probably already knew to do)...... and you'll be set! I forgot it was a library we used for my comp sci class (this project was due 2 weeks ago.. but I'm just expanding on it is all!!!)

This module provides a simple interface to create a window, load an image and experiment 
with image based algorithms.  Many of which require pixel-by-pixel manipulation.  This
is a educational module, its not intended to replace the excellent Python Image Library, in fact 
it uses PIL.

The module and its interface and some of the code were inspired/copied by/from John Zelle's graphics.py 
which serves a similar purpose in the graphics primitive world.

import Tkinter
import Image
import ImageTk

# Borrow some ideas from Zelle
# create an invisible global main root for all windows
tk = Tkinter
_root = tk.Tk()

class ImageWin(tk.Canvas):
    ImageWin:  Make a frame to display one or more images.
    def __init__(self,title,width,height):        
        Create a window with a title, width and height.
        master = tk.Toplevel(_root)
        master.protocol("WM_DELETE_WINDOW", self.close)
        tk.Canvas.__init__(self, master, width=width, height=height)
        self.foreground = "black"
        self.items = []
        self.mouseX = None
        self.mouseY = None
        self.bind("<Button-1>", self._onClick)
        self.height = height
        self.width = width
        self._mouseCallback = None
        self.trans = None

    def close(self):
        """Close the window"""
    def getMouse(self):
        """Wait for mouse click and return a tuple with x,y position in screen coordinates after
        the click"""
        self.mouseX = None
        self.mouseY = None
        while self.mouseX == None or self.mouseY == None:
        return ((self.mouseX,self.mouseY))

    def setMouseHandler(self, func):
        self._mouseCallback = func

    def _onClick(self, e):
        self.mouseX = e.x
        self.mouseY = e.y
        if self._mouseCallback:
            self._mouseCallback(Point(e.x, e.y)) 
class image:
    Create an image.  The image may be created in one of four ways:
    1. From an image file such as gif, jpg, png, ppm  for example: i = image('fname.jpb)
    2. From a list of lists
    3. From another image object
    4. By specifying the height and width to create a blank image.
    imageCache = {} # tk photoimages go here to avoid GC while drawn 
    imageId = 1
    def __init__(self,fname=None,data=[],imobj=None,height=0,width=0):
        An image can be created using any of the following keyword parameters. When image creation is 
        complete the image will be an rgb image.
        fname:  A filename containing an image.  Can be jpg, gif, and others
        data:  a list of lists representing the image.  This might be something you construct by
        reading an asii format ppm file, or an ascii art file and translate into rgb yourself.
        imobj:  Make a copy of another image.
        width: Create a blank image of a particular height and width.
        if fname:
            self.im = Image.open(fname)
            ni = self.im.convert("RGB")
            self.im = ni
        elif data:
            height = len(data)
            width = len(data[0])
            self.im = Image.new("RGB",(width,height))
            for row  in range(height):
                for col in range(width):
        elif height > 0 and width > 0:
            self.im = Image.new("RGB",(width,height))
        elif imobj:
            self.im = imobj.copy()
        self.width,self.height = self.im.size
        self.centerX = self.width/2
        self.centerY = self.height/2
        self.id = None

    def copy(self):
        """Return a copy of this image"""
        newI = image(imobj=self.im)
        return newI

    def clone(self):
	     """Return a copy of this image"""
	     newI = image(imobj=self.im)
	     return newI
    def getHeight(self):
        """Return the height of the image"""
        return self.height

    def getWidth(self):
        """Return the width of the iamge"""
        return self.width
    def getPixel(self,x,y):
        """Get a pixel at the given x,y coordinate.  The pixel is returned as an rgb color tuple
        for eaxamplle foo.getPixel(10,10) --> (10,200,156) """
        return self.im.getpixel((x,y))
    def setPixel(self,x,y,colorTuple):
        """Set the color of a pixel at position x,y.  The color must be specified as an rgb tuple (r,g,b) where 
        the rgb values are between 0 and 255."""
    def setPosition(self,x,y):
        """Set the position in the window where the center of this image should be."""
        self.centerX = x
        self.centerY = y
    def draw(self,win):
        """Draw this image in the ImageWin window."""
        ig = ImageTk.PhotoImage(self.im)
        self.imageCache[self.imageId] = ig # save a reference else Tk loses it...
        image.imageId = image.imageId + 1
        self.id = self.canvas.create_image(self.centerX,self.centerY,image=ig)

class FileImage(image):
	def __init__(self,thefile):
		image.__init__(self,fname = thefile)
class EmptyImage(image):
	def __init__(self,cols,rows):
		image.__init__(self,height = rows, width = cols)
class ListImage(image):
	def __init__(self,thelist):

# Example program  Read in an image and calulate the negative.
if __name__ == '__main__':
    win = ImageWin("My Window",480,640)
    oImage = image('lcastle.jpg')
    myImage = oImage.copy()

    for row in range(myImage.getHeight()):
        for col in range(myImage.getWidth()):
             v = myImage.getPixel(col,row)
             x = map(lambda x: 255-x, v)

is there anyone else who could take a look at this module and mess around with what i have? thanks


I did manage to test your code and found the problem. With zoom > 3 you will have to expand the code accordingly ...

# double the size of an image attempt

from image import *

def enlarge(oImage, w, h, x, y, zoom):
    nImage = EmptyImage(w*zoom, h*zoom)
    for q in range(w):
        x = x + zoom
        y = 0

        for z in range(h):
            color = oImage.getPixel(q, z)
            #print x, y, q, z, color  # test
            red = color[0]
            green = color[1]
            blue = color[2]
            # this takes care of zoom=2
            nImage.setPixel(x , y, (red, green, blue))
            nImage.setPixel(x+1, y+1, (red, green, blue))
            nImage.setPixel(x+1, y, (red, green, blue))
            nImage.setPixel(x, y+1, (red, green, blue))
            if zoom > 2:
                # problem here, skips pixel loacations and defaults to black (0,0,0)
                # (x+2,y+1) and (x+1,y+2) are skipped on zoom = 3
                # even more pixels are skipped on zoom = 4
                for lea in range(2, zoom):
                    #print lea,  # test
                    nImage.setPixel(x+lea, y+lea, (red,green,blue))
                    nImage.setPixel(x, y+lea, (red, green, blue))
                    nImage.setPixel(x+1, y+lea, (red, green, blue))  # added for zoom=3
                    nImage.setPixel(x+lea, y, (red, green, blue))
                    nImage.setPixel(x+lea, y+1, (red, green, blue))  # added for zoom=3
            y = y + zoom

    r = nImage
    winner = ImageWin("Big Picture", w*zoom, h*zoom)

def main():
    #picname= raw_input("Enter Picture name with .jpg, .bmp, or ending: ")
    picname = "white80x80.jpg"  # uses a totally white 80x80 test jpeg
    oImage = FileImage(picname)
    h = oImage.getHeight()
    w = oImage.getWidth()
    win = ImageWin("Original", w, h)
    zoom = input("Number of times to zoom: ")
    zoom = 3  # added for testing
    x = -zoom
    y = 0

    enlarge(oImage, w, h, x, y, zoom)


This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.