6

So I have a .jpg/.png and I opened it up in Text Edit which I provided below:

Is there anyway I can save these exotic symbols to a string in Python to later write that to a file to produce an image?

I tried to import a string that had the beta symbol in it and I got an error that send Non-ASCII so I am assuming the same would happen for this.

Is there anyway to get around this problem?

Thanks

Portion of Image.png in Text Edit:

enter image description here

O.rka
  • 29,847
  • 68
  • 194
  • 309
  • 1
    Sounds like you just want to copy the image into a different file -- because if it is, then you don't really need to read the whole thing into memory all at once. – martineau Aug 24 '12 at 23:59
  • I’m voting to close this question because no attempt to solve whatsoever by OP - no code. – Danny Varod Dec 24 '20 at 11:59

2 Answers2

24

What you are looking at in your text edit is a binary file, trying to represent it all in human readable characters.

Just open the file as binary in python:

with open('picture.png', 'rb') as f:
    data = f.read()

with open('picture_out.png', 'wb') as f:
    f.write(data)
jdi
  • 90,542
  • 19
  • 167
  • 203
  • 3
    This kind of thing is easier in Python 3, which will shout at you the second you mix up binary data with text. One of the many reasons Python 3 rules. –  Aug 24 '12 at 21:11
  • 6
    @delnan: And when Python 3 is supported by every package and library out there..it will **actually** rule :-) One of the important reasons it currently doesn't rule – jdi Aug 24 '12 at 21:19
0

You can read to file in binary format by providing the rb flag to open and then just save what ever comes out of the file into a text file. I don't know what the point of this would be but there you go

# read in image data
fh = open('test.png','rb')
data = fh.read()
fh.close()

# write gobbledigoock to text file
fh = open('test.txt','w')
fh.write(data)
fh.close
fh.close()
Matti Lyra
  • 12,828
  • 8
  • 49
  • 67