title: Convert image to string (for Symfony2 Response)
body: <p>I'm building a script for image resizing in Symfony2.</p>
  
  <p>As I'd like to be able to use standard Symfony2 response system...</p>
  
  <pre><code>$headers = array('Content-Type'     =&gt; 'image/png',
                   'Content-Disposition' =&gt; 'inline; filename="image.png"');
  
  return new Response($img, 200, $headers);  // $img comes from imagecreatetruecolor()
  </code></pre>
  
  <p>...I need a string to send as a response. Unfortunately, functions like <code>imagepng</code> do only write files or output directly to the browser, not return strings.</p>
  
  <p>So far the only solutions I was able to think of are</p>
  
  <p>1] save the image to a temporary location and then read it again</p>
  
  <pre><code>imagepng($img, $path);
  return new Response(file_get_contents($path), 200, $headers);
  </code></pre>
  
  <p>2] use output buffering</p>
  
  <pre><code>ob_start();
  imagepng($img);
  $str = ob_get_contents();
  ob_end_clean();
  
  return new Response($str, 200, $headers);
  </code></pre>
  
  <p>Is there a better way?</p>