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 Stata链式中介效应代码修改
  • ¥15 latex投稿显示click download
  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 添加组件无法加载页面,某块加载卡住
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用