From 68fe8618c67718557f7c38eef3d784c597355129 Mon Sep 17 00:00:00 2001 From: Alex Eidt Date: Sat, 1 Oct 2022 11:35:47 -0700 Subject: [PATCH] Add example to README, copy buffer in Write --- README.md | 17 +++++++++++++++++ imageio.go | 20 +++----------------- 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index f5b8809..ec55543 100644 --- a/README.md +++ b/README.md @@ -167,6 +167,23 @@ for i := 1; i <= 10; i++ { } ``` +Write all frames of `video.mp4` as `jpg` images. + +```go +video, _ := vidio.NewVideo("video.mp4") + +img := image.NewRGBA(image.Rect(0, 0, video.Width(), video.Height())) +video.SetFrameBuffer(img.Pix) + +frame := 0 +for video.Read() { + f, _ := os.Create(fmt.Sprintf("%d.jpg", frame)) + jpeg.Encode(f, img, nil) + f.Close() + frame++ +} +``` + # Acknowledgements * Special thanks to [Zulko](http://zulko.github.io/) and his [blog post](http://zulko.github.io/blog/2013/09/27/read-and-write-video-frames-in-python-using-ffmpeg/) about using FFmpeg to process video. diff --git a/imageio.go b/imageio.go index 03ecc4a..b586593 100644 --- a/imageio.go +++ b/imageio.go @@ -6,7 +6,6 @@ import ( "os" "path/filepath" - "image/color" "image/jpeg" "image/png" ) @@ -61,27 +60,14 @@ func Write(filename string, width, height int, buffer []byte) error { defer f.Close() image := image.NewRGBA(image.Rect(0, 0, width, height)) - index := 0 - for h := 0; h < height; h++ { - for w := 0; w < width; w++ { - r, g, b := buffer[index+0], buffer[index+1], buffer[index+2] - image.Set(w, h, color.RGBA{r, g, b, 255}) - index += 4 - } - } + copy(image.Pix, buffer) switch filepath.Ext(filename) { case ".png": - if err := png.Encode(f, image); err != nil { - return err - } + return png.Encode(f, image) case ".jpg", ".jpeg": - if err := jpeg.Encode(f, image, nil); err != nil { - return err - } + return jpeg.Encode(f, image, nil) default: return fmt.Errorf("unsupported file extension: %s", filepath.Ext(filename)) } - - return nil }