在這種情況下,你不需要實現自己的io.Reader
。使用io.Pipe
和jpeg.Encode
,例如
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\n", 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
}
您需要將圖像編碼爲某種格式。如果你想要一個jpeg,那麼看一下jpeg包:https://golang.org/pkg/image/jpeg/#Encode – JimB
謝謝@JimB所以,例如,我編碼爲一個bytes.Buffer,並且可以直接使用它因爲它也實現了io.Reader,對吧? – tsdtsdtsd