title: How to convert Python numpy array to base64 output
body: <p>I basically need to do <a href="https://stackoverflow.com/questions/12710001/how-to-convert-uint8-array-to-base64-encoded-string">this</a> but in Python instead of Javascript.  I receive a base64 encoded string from a socketio connection, convert it to uint8 and work on it, then need to convert it to base64 string so I can send it back.  </p>
  
  <p>So, up to this point I've got this (I'm getting the <code>data</code> dictionary from the socketio server):</p>
  
  <pre><code>import pickle
  import base64
  from io import BytesIO
  from PIL import Image
  
  base64_image_string = data["image"]
  image = Image.open(BytesIO(base64.b64decode(base64_image_string)))
  img = np.array(image)
  </code></pre>
  
  <p>How do I reverse this process to get from <code>img</code> back to <code>base64_image_string</code>?</p>
  
  <p><strong>UPDATE:</strong><br>
  I have solved this in the following manner (continuing from the code snippet above):</p>
  
  <pre><code>pil_img = Image.fromarray(img)
  buff = BytesIO()
  pil_img.save(buff, format="JPEG")
  new_image_string = base64.b64encode(buff.getvalue()).decode("utf-8")
  </code></pre>
  
  <p>Somewhat confusingly, <code>new_image_string</code> is not identical to <code>base64_image_string</code> but the image rendered from <code>new_image_string</code> looks the same so I'm satisfied!</p>