-1

I get values from the Oracle blob, below.
It's a JPEG file that somebody stored as a signed char, rather than unsigned.
How can I convert it into a image?

[-1,-40,-1,-32,0,16,74,70,73,70,0,1,1,0,0,1,0,1,0,0,-1,-37,0,67,0,1,...]

View raw data on Pastebin

showdev
  • 28,454
  • 37
  • 55
  • 73
  • Actually it's a JPEG file that somebody has stored as a signed char, rather than unsigned. – Mark Setchell Jan 24 '20 at 22:21
  • You might be able to [read a raw image using PIL](https://stackoverflow.com/q/3397157/924299), but specifics will probably depend on the [colorspace and encoding](https://stackoverflow.com/a/3397322/924299) as well as the [image format](https://stackoverflow.com/a/14319467/924299). – showdev Jan 25 '20 at 00:41

1 Answers1

3

It depends whether you mean you want to save the data to disk as a JPEG or further process it in memory as an image.

As it is, the image has been (incorrectly) stored as a signed char instead of as an unsigned char - I can tell that because there are negative values in there. I can tell it is a JPEG because JPEGs have the string JFIF near the start and J=74, F=70 and I=73 in ASCII - you will see those values near the start.

So, first I did a list comprehension to correct the values like this:

# Data from pastebin
im = [-1,-40,-1,-32,0,16,74,70,73,70,0...]

# Correct negative values to be "256+current"
corrected = [256+x if x<0 else x for x in im]

Then, assuming you want to write the image to disk, it is already JPEG-encoded so we just need to convert the list to bytes and write those to disk

#!/usr/bin/env python3

# Data from pastebin
im = [-1,-40,-1,-32,0,16,74,70,73,70,0 ...]

# Correct negative values to be "256+current"
corrected = [256+x if x<0 else x for x in im]

# Convert corrected data to bytes and save to disk as "result.jpg"
with open('result.jpg', 'wb') as f:
    f.write(bytes(corrected))

If, on the other hand, you want to make a PIL Image and process it, you can wrap the bytes in a BytesIO and ask PIL to open that:

from PIL import Image
from io import BytesIO

# Data from pastebin
im = [-1,-40,-1,-32,0,16,74,70,73,70,0 ...]

# Correct negative values to be "256+current"
corrected = [256+x if x<0 else x for x in im]

# Convert the corrected list to "bytes", wrap in BytesIO and ask PIL to open as PIL Image
pImage = Image.open(BytesIO(bytes(corrected)))

# Now we can display it
pImage.show() 

# Or save it
pImage.save('result.jpg')

enter image description here

Note that if you prefer to use OpenCV rather than PIL, you would use cv2.imdecode() in place of PIL Image.open().

Keywords: Python, image processing, convert list of numbers to image, convert blob to image, convert Oracle database blob to image.

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432