title: Looking for better way to save an in memory image to file
body: <p>The goal of the code is to download an image, stick it to a larger parent image and save the result.</p>
  
  <p>After quite a few failures I ended up with the following code that does work.</p>
  
  <p>However, is there a better way than using <code>bytes.Buffer</code> and a <code>writer</code> to save the target image to a file / pass it to an httpResponse?</p>
  
  <pre class="lang-golang prettyprint-override"><code>package main
  
  import (
      "image"
      "image/draw"
      "image/jpeg"
      "os"
      // "image/color"
      // "io/ioutil"
      // "fmt"
      "bufio"
      "bytes"
      "log"
      "net/http"
  )
  
  func main() {
      // Fetch an image.
      resp, err := http.Get("http://katiebrookekennels.com/wp-content/uploads/2014/10/dog-bone4.jpg")
      if err != nil {
          log.Panic(err)
      }
      defer resp.Body.Close()
  
      // Keep an in memory copy.
      myImage, err := jpeg.Decode(resp.Body)
  
      if err != nil {
          log.Panic(err)
      }
  
      // Prepare parent image where we want to position child image.
      target := image.NewRGBA(image.Rect(0, 0, 800, 800))
      // Draw white layer.
      draw.Draw(target, target.Bounds(), image.White, image.ZP, draw.Src)
      // Draw child image.
      draw.Draw(target, myImage.Bounds(), myImage, image.Point{0, 0}, draw.Src)
  
      // Encode to jpeg.
      var imageBuf bytes.Buffer
      err = jpeg.Encode(&amp;imageBuf, target, nil)
  
      if err != nil {
          log.Panic(err)
      }
  
      // Write to file.
      fo, err := os.Create("img.jpg")
      if err != nil {
          panic(err)
      }
      fw := bufio.NewWriter(fo)
  
      fw.Write(imageBuf.Bytes())
  }
  </code></pre>