Go标准库中是否有一个函数可以将缓冲区编码为go中的任何图像格式
I'm writing a micro-service with some simple image manipulation in go.
When I come to sending the manipulated image back to the user I have to encode it correctly before writing it via a buffer.
I can detect the format easily enough, so it's not precisely a problem. Currently I use my format string and do it like this:
buffer := new(bytes.Buffer)
switch format { //format is just a string as returned by image.Decode()
case "jpeg":
err := jpeg.Encode(buffer, img, nil) //img is just an image.Image
if err != nil {
//Do some error handling
}
case "png":
err := png.Encode(buffer, img)
if err != nil {
//Do some error handling
}
//and so on...
Now this works just fine, I was about to split it out into my own function when I started to think I must have missed something here. It seems too obvious to not have a function like image.Encode(buffer, image, format)
.
It's not exactly hassle to write it, but my code will soon become unnecessarily unwieldy if I start re-implementing core language functionality.
If it's just not there because go is a nice tidy language with a small footprint, I'm cool with that.
我正在编写带有一些简单图像处理功能的微服务。 p>
当我将经过处理的图像发送回用户时,必须先对其进行正确编码,然后再通过缓冲区写入。 p>
我可以检测到 格式很容易,所以这不是问题。 当前,我使用我的格式字符串,并按以下方式进行操作: p>
buffer:= new(bytes.Buffer)
switch format {//格式只是返回的字符串 通过image.Decode()
case“ jpeg”:
err:= jpeg.Encode(buffer,img,nil)// img只是一幅图像。Image
if err!= nil {
//做一些 错误处理
}
case“ png”:
err:= png.Encode(buffer,img)
if err!= nil {
//进行一些错误处理
}
//依此类推 ...
code> pre>
现在这很好用,当我开始认为自己一定错过了某些东西时,我打算将其拆分为自己的函数。 似乎太明显了,没有像 image.Encode(buffer,image,format) code>这样的功能。 p>
编写它并不是很麻烦,但是我的代码 如果我开始重新实现核心语言功能,将很快变得不必要地麻烦。 p>
如果因为go语言是一种不错的,整洁的,占地少的语言而没有使用,那我就很酷。 p>
div>
The standard library does not contain a function for encoding an image to an arbitrary format.
One reason that the library does not have such a function is that there are different encoding options for each image format. For example the JPEG options and PNG options are different.