Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading Base64 String into Python Image Library

I'm sending images as base64 string through ajax to django. In my django view I need to resize the image and save it in the file system.

Here is a base64 string(simplified):

data:image/jpeg;base64,/9j/4AAQSkZJRg-it-keeps-going-for-few-more-lines=

I tried to open this in PIL using the below python code:

img = cStringIO.StringIO(request.POST['file'].decode('base64'))
image = Image.open(img)
return HttpResponse(image, content_type='image/jpeg')

I'm trying to display the uploaded image back, but firefox complains that 'The image cannot be displayed because it contains error'

I couldn't figure out my mistake.

SOLUTION:

pic = cStringIO.StringIO()

image_string = cStringIO.StringIO(base64.b64decode(request.POST['file']))

image = Image.open(image_string)

image.save(pic, image.format, quality = 100)

pic.seek(0)

return HttpResponse(pic, content_type='image/jpeg')
like image 490
Praveen Avatar asked Nov 11 '13 14:11

Praveen


People also ask

How do you Base64 a string in Python?

To convert a string into a Base64 character the following steps should be followed: Get the ASCII value of each character in the string. Compute the 8-bit binary equivalent of the ASCII values. Convert the 8-bit characters chunk into chunks of 6 bits by re-grouping the digits.

How do I open an image in Base64 in Python?

Base64 Decoding an Image To decode an image using Python, we simply use the base64. b64decode(s) function. Python mentions the following regarding this function: Decode the Base64 encoded bytes-like object or ASCII string s and return the decoded bytes.

How do I load an image into Base64 tag?

Use the img Tag to Display Base64 Image in HTML We can specify the URL of the image in the src attribute of the img tag. We can display base64 images by providing the information about the image in the src attribute. We need to define the accurate content type, content-encoding, and charset in the src attribute.


2 Answers

The beginning of the POSTed string (data:image/jpeg;base64,) is a header and should be removed before the decoding. The image is corrupted otherwise.

photo = request.POST['photo'].partition('base64,')[2]
image_data = b64decode(photo)
someobject.photo.save('user.jpg', ContentFile(image_data), save=True)
like image 97
Dominique PERETTI Avatar answered Oct 03 '22 15:10

Dominique PERETTI


SOLUTION:

Saving the opened PIL image to a file-like object solves the issue.

pic = cStringIO.StringIO()
image_string = cStringIO.StringIO(base64.b64decode(request.POST['file']))
image = Image.open(image_string)
image.save(pic, image.format, quality = 100)
pic.seek(0)
return HttpResponse(pic, content_type='image/jpeg')
like image 25
Praveen Avatar answered Oct 03 '22 15:10

Praveen