If you are not afraid of running a Python script, here's a quick one.
Pass in a text file where there's one base64 image per line.
This will write out a sequence of images, like image0001.png
, image0002.png
, ...
import fileinput
import base64
for index, line in enumerate(fileinput.input(), 1):
if line.startswith('data:image/png;base64,'):
with open('image{0:04}.png'.format(index), 'wb') as png:
line = line.strip()
png.write(base64.b64decode(line[22:] + '===='))
Save this into a file like decode.py
, then run it with
python3 decode.py input.txt
If your input file is CSV with a single column, that's a text file, too, so you should be able to use that directly (though CSV might have quoting you need to trim off). If you really have to accept the input in a proper Excel spreadsheet, exporting that to CSV is a manual process which is one good reason to avoid Excel if you can.
Based on your comment, here is an attempt to use the xlrd
module to read Excel directly, but I (thankfully) have nothing to test it on.
import base64
import xlrd
workbook = xlrd.open_workbook("images.xlsx")
worksheet = workbook.sheet_by_name("Sheet1")
for idx in range(1, worksheet.nrows+1):
excel_data = worksheet.cell(idx-1,0).value
if excel_data.startswith('data:image/png;base64,'):
with open('image{0:04}.png'.format(idx), 'wb') as png:
png.write(base64.b64decode(excel_data.strip()[22:] + '===='))
Your attempt was using the base64 data excel_data
instead of the index in the the argument to open
which specifies the file name. idx
runs from 1 to the number of the final row of data.
Addendum:
Some of the data seems to be erroneous. I managed to extract your pictures with the following hack, but I'm not sure if it's actually producing correct output -- this seemed to work for the images I tried, but it could introduce corruption because I am simply dropping the last base64 character.
import fileinput
import base64
import binascii
for index, line in enumerate(fileinput.input(), 1):
if line.startswith('data:image/png;base64,'):
with open('image{0:04}.png'.format(index), 'wb') as png:
line = line.strip()[22:]
try:
decoded = base64.b64decode(line + '====')
except binascii.Error:
decoded = base64.b64decode(line[0:-1] + '====')
png.write(decoded)
Best Answer
Use
xxd
with the-r
argument (and possibly the-p
argument) to convert from hex to plain binary/octets and base64 to convert the binary/octet form to base64.For a file:
For a string of hex numbers: