title: save base64 image python
body: <p>I am trying to save an image with python that is Base64 encoded. Here the string is to large to post but here is the image</p>
  
  <p><a href="https://i.stack.imgur.com/JYHLV.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/JYHLV.jpg" alt="enter image description here"></a></p>
  
  <p>And when received by python the last 2 characters are <code>==</code> although the string is not formatted so I do this</p>
  
  <pre><code>import base64
  data = "data:image/png;base64," + photo_base64.replace(" ", "+")
  </code></pre>
  
  <p>And then I do this</p>
  
  <pre><code>imgdata = base64.b64decode(data)
      filename = 'some_image.jpg'  # I assume you have a way of picking unique filenames
      with open(filename, 'wb') as f:
              f.write(imgdata)
  </code></pre>
  
  <p>But this causes this error</p>
  
  <pre><code>Traceback (most recent call last):
    File "/var/www/cgi-bin/save_info.py", line 83, in &amp;lt;module&amp;gt;
      imgdata = base64.b64decode(data)
    File "/usr/lib64/python2.7/base64.py", line 76, in b64decode
      raise TypeError(msg)
  TypeError: Incorrect padding
  </code></pre>
  
  <p>I also printed out the length of the string once the <code>data:image/png;base64,</code> has been added and the <code>spaces</code> replace with <code>+</code> and it has a length of <code>34354</code>, I have tried a bunch of different images but all of them when I try to open the saved file say that the file is damaged.</p>
  
  <p>What is happening and why is the file corrupt?</p>
  
  <p>Thanks</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Here is some base64 that also failed</p>
  
  <pre><code>iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADBQTFRFA6b1q Ci5/f2lt/9yu3 Y8v2cMpb1/DSJbz5i9R2NLwfLrWbw m T8I8////////SvMAbAAAABB0Uk5T////////////////////AOAjXRkAAACYSURBVHjaLI8JDgMgCAQ5BVG3//9t0XYTE2Y5BPq0IGpwtxtTP4G5IFNMnmEKuCopPKUN8VTNpEylNgmCxjZa2c1kafpHSvMkX6sWe7PTkwRX1dY7gdyMRHZdZ98CF6NZT2ecMVaL9tmzTtMYcwbP y3XeTgZkF5s1OSHwRzo1fkILgWC5R0X4BHYu7t/136wO71DbvwVYADUkQegpokSjwAAAABJRU5ErkJggg==
  </code></pre>
  
  <p>This is what I receive in my python script from the POST Request </p>
  
  <p>Note I have not replace the spaces with +'s</p>