0

when I wanted to have the same image 2 time in 2 differents variables so i can modify one while keeping the other as a reference. I used to to it like that:

im1 = Image.open(imagepath)
im2 = im1

and i always got issues while doing that because, if i modify one image, the other will also be modified. You can try it yourself if you want:

from PIL import Image
im1 = Image.open(r"D:\python\pixelartor\pixelartor_v3.1\pkg\trezor\trezor_0007.png")
im1.show()
im2 = im1
for x in range(100):
    for y in range(100):
        im2.putpixel((x,y),(255,0,0))
im1.show()

as you can see in the above script, i show im1, then i modify im2 and show im1 again but the first im1 and the second aren't the same but i never asked pillow to modify im1: the 2 images aren't the same

I think there is a much clever way to copy PIL.Images but i don't find anything on the web. And please don't tell me to open the image 2 times because it won't work in my case. I hope someone will hep me because i faced this issue 2 weeks ago, so i abandonned my project and i restarted the same project from scratch this week and the same problem happened, but this time, i tried to understand what was happening.

rémi couturier
  • 425
  • 3
  • 11

1 Answers1

1

I tried your code,it is my code and result:

from PIL import Image

im1 = Image.open("1.ico")
im2 = im1

print(im1)
print(im2)

for x in range(30):
    for y in range(30):
        im2.putpixel((x,y),(255,0,0))

im2.show()
im1.show()
print(im2 is im1)
# <PIL.IcoImagePlugin.IcoImageFile image mode=RGBA size=64x64 at 0x1AF1EB163C8>
# <PIL.IcoImagePlugin.IcoImageFile image mode=RGBA size=64x64 at 0x1AF1EB163C8>
# True

They have the same address,so they are the same objects. Maybe you can use deepcopy,like this:

from PIL import Image
import copy
im1 = Image.open(r"2.png")
im2 = copy.deepcopy(im1)
print(im1)
print(im2)

for x in range(30):
    for y in range(30):
        im2.putpixel((x,y),(255,0,0))

im2.show()
im1.show()
print(im2 is im1)
# <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=255x255 at 0x211FEBE60B8>
# <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=255x255 at 0x211FFCF70F0>
# False
jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49