3

I am sending base64 string from Rest call to Golang server using Angular.Now the problem is to create image using this string.

My 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(&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
}
I159
  • 29,741
  • 31
  • 97
  • 132
Mukesh Verma
  • 43
  • 1
  • 1
  • 7
  • please add you code to the question – Jadeye Feb 10 '17 at 08:15
  • Possible duplicate of [How to write a base64 decoded png image to file?](http://stackoverflow.com/questions/33149551/how-to-write-a-base64-decoded-png-image-to-file/33149620#33149620); and [Go base64 image decode](http://stackoverflow.com/questions/33319759/go-base64-image-decode/33321592#33321592). – icza Feb 10 '17 at 08:17

1 Answers1

12

I would do something like this :

b := getB64PNG()
unbased, err := base64.StdEncoding.DecodeString(b)
if err != nil {
    panic("Cannot decode b64")
}

r := bytes.NewReader(unbased)
im, err := png.Decode(r)
if err != nil {
    panic("Bad png")
}

f, err := os.OpenFile("example.png", os.O_WRONLY|os.O_CREATE, 0777)
if err != nil {
    panic("Cannot open file")
}

png.Encode(f, im)
  • Hi , Am sending the base64 image data as json fromat from angular. – Mukesh Verma Feb 10 '17 at 09:59
  • Well, then your json should have a field with that base64. make the function "getB64PNG()" return that – Maciej Długoszek Feb 10 '17 at 10:01
  • Hi , Am sending the base64 image data as json fromat from angular.I am fetching from http request by using below code decoder := json.NewDecoder(r.Body) defer r.Body.Close() var d model.ImageFile err := decoder.Decode(&d) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } – Mukesh Verma Feb 10 '17 at 10:06
  • Am using above code (written by you) is giving me errors. I am doing using below code 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) – Mukesh Verma Feb 10 '17 at 10:08
  • That is here::::::::"deals_get.go:108: cannot use bytes.NewReader(unbased) (type *bytes.Reader) as type *http.Request in assignment deals_get.go:109: cannot use r (type *http.Request) as type io.Reader in argument to png.Decode: *http.Request does not implement io.Reader (missing Read method)" FATAL: command "build" failed: exit status 2 – Mukesh Verma Feb 10 '17 at 10:13
  • I am passing base64 string directly from my json in this code::::"unbased, err := base64.StdEncoding.DecodeString(d.ImageData)" . Where d is my model variable and ImageData is base64 string. – Mukesh Verma Feb 10 '17 at 10:15
  • Change variable names. Your function probably takes in r *http.Request and as you can see i am defining another "r" variable. That is why it tells you that you are using r ( request ) as io.Reader. – Maciej Długoszek Feb 10 '17 at 10:20
  • Thanks Maciej . Its helped me. :-) – Mukesh Verma Feb 10 '17 at 10:30
  • Hi Maciej above code is creating PNG image , In my case user can select both type of image (PNG/JPG). It gives error while uploading JPG image. What to do for creating jpg image as well – Mukesh Verma Feb 10 '17 at 12:32
  • To decode JPEG you should write a similar code using : https://golang.org/pkg/image/jpeg/ package . If you are unsure what type of image it is you could always try to decode image as a PNG and if it gives you an error then try going with JPEG. – Maciej Długoszek Feb 10 '17 at 12:46
  • it is giving while reading JPG image base64 string ,decodedImageData, err := base64.StdEncoding.DecodeString(d.ImageData) ::::: invalid memory address or nil pointer dereference – Mukesh Verma Feb 10 '17 at 12:59
  • The problem is, while i am select JPG image to upload it gives me above error at golang side. But its working fine with PNG image selection . – Mukesh Verma Feb 10 '17 at 13:23
  • Same issue @MukeshVerma – Manish Champaneri Sep 03 '17 at 09:56