Home >Backend Development >Golang >How to Convert an image.Image to []byte in Go for S3 Upload?
Converting image.Image to []byte in Golang
In this article, we address the issue of converting an image.Image to []byte in Go. The pain point lies in the lines indicated by dotted lines in the provided code snippet:
image_data, err := mybucket.Get(key) if err != nil { panic(err.Error()) } // reset format of data []byte to image.Image original_image, _, err := image.Decode(bytes.NewReader(image_data)) new_image := resize.Resize(160, 0, original_image, resize.Lanczos3) - - - - - - - - - - - - - - - - - - - - - - - - - - - // reset format the image.Image to data []byte here var send_S3 []byte var byteWriter = bufio.NewWriter(send_S3) - - - - - - - - - - - - - - - - - - - - - - - - - - err = jpeg.Encode(byteWriter, new_image, nil) new_path := key + "_sm" err = mybucket.Put(new_path, send_S3, "image/jpg", "aclstring")
The objective is to transform the image.Image, new_image, into []byte format for uploading to an S3 bucket.
Solution
The key to resolving this issue is to utilize a bytes.Buffer instead of a bufio.Writer. bytes.Buffer is designed to write data in memory, while bufio.Writer simply caches data in memory before passing it along to another writer.
buf := new(bytes.Buffer) err := jpeg.Encode(buf, new_image, nil) send_s3 := buf.Bytes()
By employing bytes.Buffer, we effectively capture the encoded image into a []byte slice named send_s3. This slice can then be used to upload the image to the S3 bucket.
The above is the detailed content of How to Convert an image.Image to []byte in Go for S3 Upload?. For more information, please follow other related articles on the PHP Chinese website!