0

I have this base64toJpg function; I am getting some images in base64 format from websites and then trying to store them locally by converting them to jpg, but I get an "image: unknown format" error when using this function. How can I fix it?

func base64toJpg(data string) {

    reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data))
    m, formatString, err := image.Decode(reader)
    if err != nil {
        log.Fatal(err)
    }
    bounds := m.Bounds()
    fmt.Println("base64toJpg", bounds, formatString)

    //Encode from image format to writer
    pngFilename := "image_" + strconv.Itoa(imageNum) + ".jpg"
    imageNum++
    f, err := os.OpenFile(pngFilename, os.O_WRONLY|os.O_CREATE, 0777)
    if err != nil {
        log.Fatal(err)
        return
    }

    err = jpeg.Encode(f, m, &jpeg.Options{Quality: 75})
    if err != nil {
        log.Fatal(err)
        return
    }
    fmt.Println("Jpg file", pngFilename, "created")

}
DvdiidI
  • 63
  • 6
  • 1
    There is no decoder registered that understands your Base64 decoded image. Either it's not an image, or you haven't registered a decoder that can handle it. You have to "blank-import" certain packages to have them registered, e.g. to support PNG images, you have to do `import _ "image/png"`. – icza Oct 31 '22 at 16:26
  • I already did that; import ( "encoding/base64" "encoding/csv" "fmt" "image" "image/jpeg") This is a part of my import and still getting same error after including "image/png" – DvdiidI Nov 01 '22 at 17:41
  • Maybe it's not JPG nor PNG, we can't tell without seeing your data. Include the first couple of bytes (like ~50) of your image and we might be able to help. – icza Nov 01 '22 at 17:49
  • ok, here's how it looks: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCADIASwDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFB................................... – DvdiidI Nov 01 '22 at 17:57
  • This is not a simple Base64 encoded image, what you have is a Data URI scheme. See marked duplicates. – icza Nov 01 '22 at 17:59
  • Thanks for the reference to that question; it seems I had to parse the first part of base64 encoding to make it work – DvdiidI Nov 01 '22 at 19:24

0 Answers0