Convert base64 string to JPG

后端 未结 2 589
时光取名叫无心
时光取名叫无心 2021-02-08 15:51

I am getting the image as base64 string ( dataurl ), Below is my function that converts the dataurl into the image,

Now if the

2条回答
  •  执笔经年
    2021-02-08 16:44

    You're passing your io.Reader to png.Decode(), which begins consuming the reader, only to discover that the input is not a valid PNG, so returns an error.

    Then your partly-consumed reader is passed to jpeg.Decode(), which reads the data not yet read, which is not a valid JPEG, and returns the error you observe.

    You need to create a new reader for each decoder:

    pngI, errPng := png.Decode(bytes.NewReader(unbased))
    
    // ...
    
    jpgI, errJpg := jpeg.Decode(bytes.NewReader(unbased))
    

    Or better yet, consider the MIME type, and only call the proper decoder:

    switch strings.TrimSuffix(image[5:coI], ";base64") {
    case "image/png":
        pngI, err = png.Decode(res)
        // ...
    case "image/jpeg":
        jpgI, err = jpeg.Decode(res)
        // ...
    }
    

提交回复
热议问题