chenchiyuan
chenchiyuan

Reputation: 151

How to convert image data type from windows sql server to image using python?

I need to convert compressed image column data from windows sql server to image file and save it to file system.

data is in github gist

I am using Python 2.7.2, Pillow on mac.

Thank you !

Upvotes: 0

Views: 3513

Answers (2)

Rafael Leonhardt
Rafael Leonhardt

Reputation: 434

Worked to me using b16decode.

My exported image from sql is something like that: 'FFD8FFE000104A46494600010101004800480000FFE13...'

So I had to convert the content and saved into a file.

source = 'data.dat'
destination = 'data.jpg'
with open(source, 'r') as f:
    content = f.read()
    content = base64.b16decode(content)
    with open(destination, 'wb') as g:
        g.write(content)

Upvotes: 1

Michiel Overtoom
Michiel Overtoom

Reputation: 1619

What I did was opening your gist in my browser, then save as... to a file named 'chenchi.txt'.

I then used this program to convert the hex-encoded string to raw bytes and load them into Pillow to make an image out of it:

from PIL import Image
import StringIO
import binascii

# In your case, 's' will be the string from the field
# in the database.
s = open("chenchi.txt").read()

# chop off the '0x' at the front.
s = s[2:] 

# Decode it to binary.
binary = binascii.unhexlify(s)

# Wrap the bytes in a memory stream that can be read like a file.
bytes = StringIO.StringIO(binary)

# Use pillow to read the memory stream into an image (it autodetects the format).
im = Image.open(bytes)

# And show it. Or you could .save() it.
im.show()

Upvotes: 1

Related Questions