Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
986 views
Welcome To Ask or Share your Answers For Others

1 Answer

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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...