本文介绍了Golang将image.Image转换为[]字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
无法将image.Image转换为[]字节。问题点以虚线包裹。
$ b $
image_data,err:= mybucket.Get(key)
if err!= nil {
panic(err.Error())
}
//重置数据格式[] byte到image.Image
original_image,_,err := image.Decode(bytes.NewReader(image_data))
new_image:= resize.Resize(160,0,original_image,resize.Lanczos3)
- - - - - - - - - - - - - - - - - - - - - - - - - -
//重置格式image.Image到data []字节在这里
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)
基本上,我需要new_image为[]字节格式,以便我可以将它发送给我的S3 。
感谢您的帮助。 bytes.Buffer,而不是bufi o.Writer。在需要写入内存的写入器时使用bytes.Buffer。 bufio.Writer只是将数据缓存到内存中,然后再转发到另一个writer。
buf:= new(bytes.Buffer)
err:= jpeg.Encode(buf,new_image,nil)
send_s3:= buf.Bytes()
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.
解决方案
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()
这篇关于Golang将image.Image转换为[]字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!