Reputation: 13
I have written a program which converts .jpg image into base64. Now I want to write these on a csv file. So that one column has a file name(string) the other column has the converted image (bytes). How do I achieve that. So far I have written below codes.
from PIL import Image
import os
import base64
import csv
def main():
array=[]
pic_name=[]
#opens file in listed directory
for f in os.listdir('./jpg_Images'):
if f.endswith('.jpg'):
#making a list of a filename
pic_name.append(f)
#joining the path
xpath = os.path.join ('./jpg_Images',f)
#open .jpg file in Binary mode
image = open(xpath, 'rb')
#open binary file in read mode
image_read = image.read()
#encode the image
image_64_encode = base64.encodebytes(image_read)
#making the list of encoded image
array.append(image_64_encode)
with open('convert.csv', 'w') as f:
writer = csv.writer(f)
writer.writerows(zip(array, pic_name))
f.close()
if __name__ == '__main__':
main()
Upvotes: 1
Views: 195
Reputation: 36643
Luckily base64 encoded byte strings can be decoded to unicode with no loss of fidelity. base64 decodes to printable (and non-escaped) characters from the ASCI range. Simple change the line:
array.append(image_64_encode)
to:
array.append(image_64_encode.decode())
Upvotes: 1