Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to covert a []byte object to an image and store it as a jpeg image on disk

Tags:

image

go

jpeg

I am trying to convert an []byte object to an image and save it as a jpeg in Golang. I tried to use Decode function of image but it always returns <nil>.

func saveFrames(imgByte []byte) {
    img, _, _ := image.Decode(bytes.NewReader(imgByte))
   out, err := os.Create("./img.jpeg")

   if err != nil {
             fmt.Println(err)
             os.Exit(1)
   }
   err = jpeg.Encode(out, img)
   if err != nil {
            fmt.Println(err)
            os.Exit(1)
   }
}
like image 245
shahidammer Avatar asked Oct 23 '18 10:10

shahidammer


1 Answers

You are not passing Options,to jpeg.Encode, you can also set it to nil.

func serveFrames(imgByte []byte) {

    img, _, err := image.Decode(bytes.NewReader(imgByte))
    if err != nil {
        log.Fatalln(err)
    }

    out, _ := os.Create("./img.jpeg")
    defer out.Close()

    var opts jpeg.Options
    opts.Quality = 1

    err = jpeg.Encode(out, img, &opts)
    //jpeg.Encode(out, img, nil)
    if err != nil {
        log.Println(err)
    }

}

Don't forget to close any file, if opened.

You can use log.Fatalln(...), if you want to print error message and quit in-case of any error.

like image 122
nilsocket Avatar answered Nov 10 '22 05:11

nilsocket