title: Loading Base64 String into Python Image Library
body: <p>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. </p>
  
  <p>Here is a base64 string(simplified):</p>
  
  <pre><code>data:image/jpeg;base64,/9j/4AAQSkZJRg-it-keeps-going-for-few-more-lines=
  </code></pre>
  
  <p>I tried to open this in PIL using the below python code: </p>
  
  <pre><code>img = cStringIO.StringIO(request.POST['file'].decode('base64'))
  image = Image.open(img)
  return HttpResponse(image, content_type='image/jpeg')
  </code></pre>
  
  <p>I'm trying to display the uploaded image back, but firefox complains that <code>'The image cannot be displayed because it contains error'</code></p>
  
  <p>I couldn't figure out my mistake. </p>
  
  <p><strong>SOLUTION:</strong></p>
  
  <pre><code>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')
  </code></pre>