title: How to create jpg/png image from base64 string in file system using golang
body: <p>I am sending base64 string from Rest call to Golang server using Angular.Now the problem is to create image using this string. </p>
  
  <p>My code :</p>
  
  <pre><code>func (server *Server) uploadImage(w http.ResponseWriter, r *http.Request) {
  
      decoder := json.NewDecoder(r.Body)
      defer r.Body.Close()
      var d model.ImageFile
      err := decoder.Decode(&amp;d)
      if err != nil {
          http.Error(w, err.Error(), http.StatusBadRequest)
          return
      }
      fmt.Println(d.Source)
      fmt.Println(d.Destination)
      fmt.Println(d.Country)
  
      dir, errr := filepath.Abs(filepath.Dir(os.Args[0]))
      if errr != nil {
          fmt.Println(errr)
      }
      substring := dir[0:(len(dir) - 10)]
  
      unbased, err := base64.StdEncoding.DecodeString(d.ImageData)
      if err != nil {
          fmt.Println("Cannot decode b64")
      }
  
      r = bytes.NewReader(unbased)
      im, err := png.Decode(r)
      if err != nil {
          fmt.Println("Bad png")
      }
  
      f, err := os.OpenFile(substring+"images/"+"example.png", os.O_WRONLY|os.O_CREATE, 777)
      if err != nil {
          fmt.Println("Cannot open file")
      }
  
      png.Encode(f, im)
  
      server.R.Text(w, http.StatusOK, d.ID.Hex())
      return
  }
  </code></pre>