How do I read an image file and decode it using Python?
Asked
Active
Viewed 2e+01k times
58
-
Please specify what you mean with "read", what is your purpose? – ase Sep 17 '10 at 13:12
-
6Please specify what you mean with "decode", what do you want to do with the resulting image? – reinierpost Sep 20 '10 at 12:32
-
1Install [Pillow](https://pypi.python.org/pypi/Pillow/2.7.0). – Antti Haapala -- Слава Україні Mar 15 '15 at 07:16
-
You can `read` as binary, aka using the `rb` flags. in order to transmit the raw image data to another program via python. Python itself would need an image viewer to present that data as visual non-binary content. – NuclearPeon Jun 16 '15 at 23:03
1 Answers
53
The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.
from PIL import Image
jpgfile = Image.open("picture.jpg")
print(jpgfile.bits, jpgfile.size, jpgfile.format)

divibisan
- 11,659
- 11
- 40
- 58

TheGentleOne
- 1,735
- 2
- 11
- 7
-
1
-
17If I run that code in the same directory as a file named "picture.jpg", I get the error: `Traceback (most recent call last): File "test.py", line 2, in
import Image ImportError: No module named Image`. The os, sys imports are extraneous; you probably meant `from PIL import Image`, which requires running `easy_install PIL`, or if you're not feeling lucky (PIL requires a substantial amount of luck to install), `easy_install pillow`. – chbrown Jul 20 '14 at 21:33 -
-
1