how to convert Base 64 string to GIF in go

Viewed 117

I'm having trouble converting a base 64 string to gif i have tried the following.

unbased, err := base64.StdEncoding.DecodeString(bs64)
    if err != nil {
        panic("Cannot decode b64")
    }
    var imgCoupon image.Image
    imgCoupon, err = gif.Decode(bytes.NewReader(unbased))

    var opt gif.Options
    opt.NumColors = 256
    var buff bytes.Buffer
    gif.Encode(&buff, imgCoupon, &opt)

but when i uploaded it in the GCP/google cloud storage the GIF doesn't animate.

this is how i upload.

sw := storageClient.Bucket(bucket).Object("test"+"_file"+".gif").NewWriter(ctx)

if _, err := io.Copy(sw, &buff); err != nil {
    c.JSON(http.StatusInternalServerError, gin.H{
        "message": err.Error(),
        "error":   true,
    })
    return
}

the result:

result

how it should be:

should be

1 Answers

The issue is with how it's being decoded. gif.Decode returns an image.Image, but gif.DecodeAll returns a gif.GIF type.

Similarly, gif.EncodeAll is used to write multiple frames.

This is the code that works for me:

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

// Use DecodeAll to load the data into a gif.GIF
imgCoupon, err := gif.DecodeAll(bytes.NewReader(unbased))
imgCoupon.LoopCount = 0

// EncodeAll to the buffer
var buff bytes.Buffer
gif.EncodeAll(&buff, imgCoupon)
    
Related