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

从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

  • 写回答

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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图的问题
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名