title: Converting matplotlib png to base64 for viewing in html template
body: <h3>Background</h3>
  <p>Hello, I am trying to make a simple web app, following a tutorial, that calculates a dampened vibration equation and returns a png of the result to the html page after it has been converted to a Base64 string.</p>
  <h3>Problem</h3>
  <p>The app functions normally except that when the result is calculated, a broken image icon is returned, likely because the Base64 string is not valid.</p>
  <h3>Troubleshooting</h3>
  <p>I have converted another png image to a Base64 string using an online converter and used <code>&lt;img src=&quot;data:image/png;base64, BASE64_STRING&quot;/&gt;</code> to display the image successfully. I believe the template is appropriately formatted. I have also read other SO answers <a href="https://stackoverflow.com/questions/20107414/passing-a-matplotlib-figure-to-html-flask">here</a> and <a href="https://stackoverflow.com/questions/28091129/what-is-the-difference-among-idioms-for-serving-a-matplotlib-image-with-flask">here</a> and tried implementing those without success.</p>
  <h3>Relevant code</h3>
  <p><strong>Here is where the image string is returned</strong></p>
  <pre><code>from numpy import exp, cos, linspace
  import matplotlib.pyplot as plt
  
  
  def damped_vibrations(t, A, b, w):
      return A*exp(-b*t)*cos(w*t)
  
  
  def compute(A, b, w, T, resolution=500):
      &quot;&quot;&quot;Return filename of plot of the damped_vibration function.&quot;&quot;&quot;
      t = linspace(0, T, resolution+1)
      u = damped_vibrations(t, A, b, w)
      plt.figure()  # needed to avoid adding curves in plot
      plt.plot(t, u)
      plt.title('A=%g, b=%g, w=%g' % (A, b, w))
  
      from io import BytesIO
      figfile = BytesIO()
      plt.savefig(figfile, format='png')
      figfile.seek(0)  # rewind to beginning of file
      import base64
      #figdata_png = base64.b64encode(figfile.read())
      figdata_png = base64.b64encode(figfile.getvalue())
      return figdata_png
  </code></pre>
  <p><strong>Here is where the image is displayed</strong></p>
  <pre><code>{% if result != None %}
  &lt;img src=&quot;data:image/png;base64,{{ result }}&quot;\&gt;
  {% endif %}
  </code></pre>
  <p>If needed, I can provide the controller file as well. Thanks for any help!</p>