doufei8250
2017-10-18 14:49
浏览 116
已采纳

从image.RGBA实现io.Reader

I need a little hint. I'm creating thumbnails of images in Go and would like to pass them to jpegoptim for crushing.

jpegoptim has the --stdin and --stdout flags, which I would like to use. Now, I don't want to save the generated image to disk first, but convert my *image.RGBA to something that implements io.Reader, so I can pass it to exec.Cmd.Stdin

I'm a little lost on how I could achieve this, would be great if someone can point me in the right direction.

Thanks

图片转代码服务由CSDN问答提供 功能建议

我需要一些提示。 我正在Go中创建图像的缩略图,并希望将其传递给jpegoptim进行压缩。

jpegoptim具有--stdin和--stdout标志,我想使用它们。 现在,我不想首先将生成的图像保存到磁盘,而是将我的* image.RGBA转换为实现io.Reader的东西,因此可以将其传递给exec.Cmd.Stdin

我对如何实现此目标有些迷茫,如果有人可以将我指向正确的方向,那就太好了。

谢谢

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dsns47611 2017-10-19 13:31
    最佳回答

    In this case, you don't need to implement your own io.Reader. Use io.Pipe and jpeg.Encode, e.g.

    func main() {
        //Prepare image ...
        img := ...
    
        //Prepare output (file etc.) ...
        outFile := ...
    
        //Use pipe to connect JPEG encoder output to cmd's STDIN
        pr, pw := io.Pipe()
    
        //Exec jpegoptim in goroutine
        done := make(chan bool, 1)
        go func() {
            //execute command
            cmdErr := bytes.Buffer{}
            cmd := exec.Command("jpegoptim", "--stdin", "--verbose")
            cmd.Stdin = pr       //image input from PIPE
            cmd.Stderr = &cmdErr //message
            cmd.Stdout = outFile //optimize image output
    
            if err := cmd.Run(); err != nil {
                // handle error
            }
            fmt.Printf("Result: %s
    ", cmdErr.String())
            close(done)
        }()
    
        //ENCODE image to JPEG then write to PIPE
        o := jpeg.Options{Quality: 90}
        jpeg.Encode(pw, img, &o)
    
        //When done, close the PIPE
        if err := pw.Close(); err != nil {
            // handle error
        }
    
        //Wait for jpegoptim
        <-done
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题