Home > Backend Development > Golang > How to Convert an image.Image to []byte in Go for S3 Upload?

How to Convert an image.Image to []byte in Go for S3 Upload?

Susan Sarandon
Release: 2024-11-30 21:13:18
Original
903 people have browsed it

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")
Copy after login

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()
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template