Carl Rendell
Carl Rendell

Reputation: 31

Convert a JSON String to an image in Python

I am receiving a JSON file from SQL Server which contains string representations of images that I need to save to disk.

The JSON stream is encoded with Base64 with the "FOR JSON AUTO" - below is the SP that is generating the JSON where the images have been stored in the database:

SELECT @JSON_OUT =
(SELECT W.W_WEB_STYLE_NAME,I.PIC_TYPE,I.IMAGE   
FROM STYLE_WEB W
   INNER JOIN dbo.IMAGES I ON I.STYLEID = W.StyleID
     FOR JSON AUTO)

I can decode with string with base64, but the resulting bytes cannot be read by PIL as an image.

Reading the byte data there seems to be a header with "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", and "System.Drawing.Bitmap", but the file is not read as a bitmap (bmp) as I would expect.

I also compared some bmp image files and did not find those System.Drawing and/or System.Drawing.Bitmap strings in the file.

The encoded image string from the JSON is in the link below:

https://drive.google.com/file/d/1iOgk7RE0XLV_AaMwDH4xjPIqpMeRBUcp/view?usp=sharing

And the decoded data that I'm trying to read with PIL is here:

https://drive.google.com/file/d/1_rVAFqGNrYRwEx9BRjoImNj-gmbHke0j/view?usp=sharing

I have been successful encoding, decoding, and using PIL to handle all types of image strings, but this one has me baffled. Hoping someone has the / an answer for this one.

The code I've used so far to test the image and try to open it is as follows:

image = base64.standard_b64decode(imageDataString)
print(imghdr.what(None,h=image) # returns none
im = Image.open(BytesIO(image)) # returns "cannot identify image file error from PIL

UPDATE: 12/4/2020

Not sure if this is the best way to update this question (comment if not)?

As it turns out - the database developer was "decorating" the original images by wrapping them with a "Bitmap wrapper" so that the images would appear in his .Net application components.

I asked him to store the images "un-wrapped", and then return those to me from his stored procedure. Once that change was made, I no longer had any issues decoding the image string from json, and saving the images to disk.

So... the problem of extracting the jpeg image from the Bitmap "wrapper" was not solved, but I don't need to solve it for my application.

Upvotes: 3

Views: 433

Answers (2)

user2845090
user2845090

Reputation: 168

Btw it looks like the file is actually a .NET binary serialization of an System.Drawing.Bitmap object.

The spec for the format.

Upvotes: 1

JeffUK
JeffUK

Reputation: 4241

It seems to be a JFIF file with some headers, also padded out with zeroes at the end.

The image file starts at FF D8 FF E0 ?? ?? 'J' 'F' 'I' 'F' 00 as per http://fileformats.archiveteam.org/wiki/JFIF

Upvotes: 0

Related Questions