duancoubeng5909
duancoubeng5909
2014-04-08 18:36

Golang将image.Image转换为[] byte

已采纳

Having trouble converting an image.Image to []byte. The problem spot is wrapped in dotted lines.

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")

Basically, I need new_image to be in []byte format so that I can send it up to my S3 bucket.

Thanks for the help.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • douman6679 douman6679 7年前

    You want a bytes.Buffer, not a bufio.Writer. bytes.Buffer is used when you need a writer that writes to memory. bufio.Writer just caches data in memory before forwarding it to another writer.

    buf := new(bytes.Buffer)
    err := jpeg.Encode(buf, new_image, nil)
    send_s3 := buf.Bytes()
    
    点赞 1 评论 复制链接分享
  • dongrongdao8902 dongrongdao8902 5年前

    Adding on to Stephen's code, if you're using the aws s3 go SDK to put an object, your code would look like:

    // create buffer
    buff := new(bytes.Buffer)
    
    // encode image to buffer
    err = png.Encode(buff, new_image)
    if err != nil {
        fmt.Println("failed to create buffer", err)
    }
    
    // convert buffer to reader
    reader := bytes.NewReader(buf.Bytes())
    
    // use it in `PutObjectInput`
    putInput := s3.PutObjectInput{
        Bucket: aws.String("my_bucket"),
        Body:   reader,
    }
    
    // send response
    resp, err := svc.PutObject(&putInput)
    
    点赞 评论 复制链接分享

相关推荐