How to Copy and Paste Images with Pillow Library in Python


In this example, we will get to know how to display images using the library Pillow in Python.
An image can be copied using the copy() method of the Image module and can be pasted using the paste() method of the Image module. To use the crop() method to cut out a rectangular square in the image, the usage is as follows:

  • copy()
  • paste(image, box)
  • crop(box)

The box is a rectangular box in the image, which is a tuple with 4 elements: (left, top, right, bottom), which represents the coordinates of the upper left and lower right corners of the rectangle. In the case of the paste() method, the box can also be a tuple with two elements: ((left, top), (right, bottom)).

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# handleImages.py

from tkinter import *
from PIL import Image, ImageTk

win = Tk()
win.title(string = "Image Copy and Paste")

# open an image
path = "F:/logos/"
imgFile = Image.open(path + "superman.png")

# create the first image instance
img1 = ImageTk.PhotoImage(imgFile)

# get width and height of the image
width, height = imgFile.size
# set the cropped area
box1 = (0, 0, width, int(height/2))

part = imgFile.crop(box1)

part= part.transpose(Image.ROTATE_180)
# paste the first part to the image
imgFile.paste(part, box1)

# create the second image instance
img2 = ImageTk.PhotoImage(imgFile)

label1 = Label(win, width=400, height=400, image=img1, borderwidth=1)
label2 = Label(win, width=400, height=400, image=img2, borderwidth=1)
label1.pack(side=LEFT)
label2.pack(side=LEFT)

win.mainloop()

4. Data

superman.png: this is the image that we’re going to copy and paste.

5. Results

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments