英文:
Is there a function in the Go standard library that will encode a buffer to any image format in go
问题
我正在使用Go编写一个微服务,其中包含一些简单的图像处理操作。
当我要将处理后的图像发送回用户时,我必须正确地对其进行编码,然后通过缓冲区进行写入。
我可以很容易地检测到图像的格式,所以这不是一个问题。目前,我使用自己的格式字符串,并按照以下方式进行编码:
buffer := new(bytes.Buffer)
switch format { // format是image.Decode()返回的字符串
case "jpeg":
err := jpeg.Encode(buffer, img, nil) // img是image.Image类型的图像
if err != nil {
// 处理错误
}
case "png":
err := png.Encode(buffer, img)
if err != nil {
// 处理错误
}
// 其他格式...
}
目前这个方法运行良好,我本来打算将其拆分为自己的函数,但是我开始思考是否有什么地方我漏掉了。似乎不可能没有一个像image.Encode(buffer, image, format)
这样的函数。
如果只是因为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.
答案1
得分: 2
标准库中没有包含将图像编码为任意格式的函数。
库中没有这样的函数的一个原因是每种图像格式都有不同的编码选项。例如,JPEG 格式的选项和 PNG 格式的选项是不同的。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论