I am using go's standard library to re-encode user-supplied images to a standard format:
import (
"io"
"image"
"image/jpeg"
)
func (imgReader io.Reader, imgWriter io.Writer) error {
decodedImg, _, err := image.Decode(imgReader)
if err != nil {
return errors.Wrap(err, "error decoding image")
}
// whole image is currently in memory here as `decodedImg`
if err := jpeg.Encode(imgWriter, decodedImg, &jpeg.Options{Quality: 90}); err != nil {
return errors.Wrap(err, "failed to encode jpeg")
}
return nil
}
It bothers me that the entire image must seemingly be loaded into memory before I can encode and begin uploading it. I wish image.Decode() would give me a way to stream the parts of the image that have been downloaded into the encoder so that I could begin encoding and uploading the image before all of it is fully pulled into memory. Is this kind of streaming decode/encode possible, or is it the nature of image encoding that I need a fully decoded image before jpeg encoding will work? If I can stream it, hopefully I can be less strict about imposing size restrictions on the incoming image.