Why is there no "Encode" in the "image" package?

The “image” package in the standard library has a “Decode” function. Why does it not have an “Encode” function as well?

The first argument to “Encode” could be the format that we want the image encoded in; just as in “Decode”, the package can consult the formats and corresponding functions that have been registered with it, to process such a request.

I looked on the Go issue tracker to see if this ever came up before and I found this: image: Make image encoding methods consistent across JPG, GIF, and PNG · Issue #12572 · golang/go · GitHub.

From the issue:

nigeltao commented on Sep 10, 2015

I can certainly see the appeal, and I’m not ruling it out, but I’m not overly excited about uniform ways to encode.

The image package (not the image/foo packages) has a Decode function, and the RegisterFormat mechanism, because it’s common to want to a decode an image, whether a file on disk or downloaded from the network, without knowing what exact format it is beforehand.

But for encoding, in my experience, you usually know exactly what format to encode in, because there’s usually only one. Or if you really need to encode multiple formats, it’s not hard to write this in your package main:

if encodePNG {
} else {

Also, as adg said, if you really want a FormatEncoder interface, it’s very easy to do so in your own code, outside of the image packages.

Sure, in hindsight, it might have been nice if the image/* packages’ encoding APIs were made consistent before we froze for Go 1.0, but at this point, I don’t think there’s much net benefit in explicitly deprecating something now.

If we were to introduce a new type, I’d call it image.Encoder instead of image.FormatEncoder, but there’s also a related idea of introducing an image.Decoder type or an image.DecodeImage(io.Reader, *image.DecodeImageOptions) function to add options to the decoding process, such as specifying a destination buffer, or a maximum decoded size. There is more discussion on issue #5050. Perhaps there’s a larger problem to be solved.

BTW, if you’re not already aware of them, there’s also BMP, WEBP and TIFF codecs under golang.org/x/image.

1 Like