在Go标准库中是否有一个函数可以将缓冲区编码为任何图像格式的Go代码?

huangapple go评论96阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年6月22日 06:08:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/30969811.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定