Getting "write() argument must be str, not bytes" in simple Pillow module example

Viewed 164

I'm pretty new to Python, and I'm trying to generate some images, so I was testing some Pillow functions.

This is one of the very first examples presented in Pillow's documentation:

 from PIL import Image, ImageDraw

    with Image.open("C:\\Users\\USER\\Desktop\\Quick_edits\\blank_square.jpg") as im:
    
        draw = ImageDraw.Draw(im)
        draw.line((0, 0) + im.size, fill=128)
        draw.line((0, im.size[1], im.size[0], 0), fill=128)
    
        # write to stdout
        im.save(sys.stdout, "PNG")

And I keep getting this error:

Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\PIL\Image.py", line 2158, in save
    save_handler(self, fp, filename)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\PIL\PngImagePlugin.py", line 1179, in _save
    fp.write(_MAGIC)
TypeError: write() argument must be str, not bytes

Please, help me. I've seen seimilar errors been addressed, but this is supposedly a simple example and can't find how to fix this...

1 Answers

If your goal is to simply view the image, try using image.show() instead:

 from PIL import Image, ImageDraw

    with Image.open("C:\\Users\\USER\\Desktop\\Quick_edits\\blank_square.jpg") as im:
    
        draw = ImageDraw.Draw(im)
        draw.line((0, 0) + im.size, fill=128)
        draw.line((0, im.size[1], im.size[0], 0), fill=128)
    
        im.show()
Related