1

I am using django. I was trying to compress an icon uploaded by a user to a smaller size using Pythons Image library.

Following is my code:

def resizeImage(icon,ext):
     path= os.path.join(settings.SITE_ROOT,'karnadash/static/tempfiles/temp'+ext)
     destination = open(path,'wb+')
     for chunk in icon.chunks():
         destination.write(chunk)
     destination.close()
     image = Image.open(path)
     image= image.resize((50, 50), Image.ANTIALIAS)
     image.save(path)
     return image

Problem is I am getting an internal server error. The last part of the stack trace is as follows:

 line 31, in resizeImage
     image.save(path)
 File "C:\Python27\lib\site-packages\PIL\Image.py", line 1446, in save
     fp = builtins.open(fp, "wb+")
IOError: [Errno 22] invalid mode ('wb') or filename: 'C:/Users/Silent/Documents/Python/karnadash/karnadash/static/tempfiles/temp.jpg'

Can anybody please explain why this is happening?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Sohaib
  • 4,556
  • 8
  • 40
  • 68

3 Answers3

2

What solved it for me was switching from backslashes to forward slashes! Who would've thought?!

Similar post: ioerror invalid mode w

Community
  • 1
  • 1
Stef g
  • 29
  • 3
  • This is clearly not related to the question OP is asking about, since the path shown here uses forward slashes. The problem with using backslashes is *extremely* well covered by other, better questions. – Karl Knechtel Aug 28 '22 at 21:30
1

Check your file path if it's valid:

C:/Users/Silent/Documents/Python/karnadash/karnadash/static/tempfiles/temp.jpg

Perhaps it contains one karnadash too much.

matino
  • 17,199
  • 8
  • 49
  • 58
  • That won't change anything. I have tried a similar thing from the python IDLE and it worked fine. And Django does not allow backslahes in absolute paths. – Sohaib Jul 04 '13 at 11:24
  • No its fine. Actually the error is very inconsistent should I post a complete edit I have discovered some new things. – Sohaib Jul 04 '13 at 11:33
-1

I had a similar problem when I was trying to save some figures in a fowder. Some figures I could save, but couldn't save others, and I was using the same code. I realized that the name of the figure and the backslash were in conflict with a reserved code.

IOError: [Errno 22] invalid mode ('wb') or filename: '02102016\nDTG.png'

I think "\n" was interpreted as "enter". The problem had been solved when I changed it to forward slash.

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60