小编典典

调整图像大小

go

我在这里使用Go调整大小包:https//github.com/nfnt/resize

  1. 我正在从S3中提取图像,如下所示:

    image_data, err := mybucket.Get(key)
    

    // this gives me data []byte

  2. 之后,我需要调整图像大小:

    new_image := resize.Resize(160, 0, original_image, resize.Lanczos3)
    

    // problem is that the original_image has to be of type image.Image

  3. 将图像上传到我的S3存储桶

    err : = mybucket.Put('newpath', new_image, 'image/jpg', 'aclstring')
    

    // problem is that new image needs to be data []byte

如何将数据转换[]byte为—> image.Image并转换回---->数据[]byte


阅读 250

收藏
2020-07-02

共1个答案

小编典典

阅读http://golang.org/pkg/image

// you need the image package, and a format package for encoding/decoding
import (
    "bytes"
    "image"
    "image/jpeg" // if you don't need to use jpeg.Encode, use this line instead 
    // _ "image/jpeg"

    "github.com/nfnt/resize"


)

// Decoding gives you an Image.
// If you have an io.Reader already, you can give that to Decode 
// without reading it into a []byte.
image, _, err := image.Decode(bytes.NewReader(data))
// check err

newImage := resize.Resize(160, 0, original_image, resize.Lanczos3)

// Encode uses a Writer, use a Buffer if you need the raw []byte
err = jpeg.Encode(someWriter, newImage, nil)
// check err
2020-07-02