diff --git a/README.md b/README.md index 0ab6bfd..71a3c54 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,3 @@ **go-marvel** is a [Go](https://golang.org) client library for the [Marvel REST API](https://developer.marvel.com/) -See [`example/main.go`](https://github.com/ImJasonH/go-marvel/blob/master/example/main.go), which downloads all issue covers of a series, by series ID (default is "Uncanny X-Men"), and begins to construct a GIF image of them. (TODO) +See [`example/main.go`](https://github.com/ImJasonH/go-marvel/blob/master/example/main.go), which downloads all issue covers of a series, by series ID (default is "Uncanny X-Men"), and constructs a GIF image of them in reverse order. diff --git a/example/main.go b/example/main.go index 5abc418..6e7f77a 100644 --- a/example/main.go +++ b/example/main.go @@ -1,6 +1,8 @@ package main import ( + "bufio" + "bytes" "flag" "fmt" "image" @@ -37,8 +39,10 @@ func main() { fmt.Printf("error: %v", err) return } - imgs = append(imgs, img) - fmt.Printf("fetched %v - %s\n", *iss.IssueNumber, iss.Thumbnail.URL(marvel.PortraitIncredible)) + if img != nil { + imgs = append(imgs, img) + fmt.Printf("fetched %v - %s\n", *iss.IssueNumber, iss.Thumbnail.URL(marvel.PortraitIncredible)) + } } if len(r.Data.Results) < limit { break @@ -61,7 +65,15 @@ func fetchImage(url string) (image.Image, error) { } defer resp.Body.Close() - img, err := jpeg.Decode(resp.Body) + b := bufio.NewReaderSize(resp.Body, 1) + if _, err := b.Peek(1); err == bufio.ErrBufferFull { + return nil, nil + } + + img, err := jpeg.Decode(b) + if err != nil { + return nil, nil + } return img, err } @@ -72,8 +84,23 @@ func writeGIF(filename string, imgs []image.Image) error { } defer f.Close() - pimgs := []*image.Paletted{} - // TODO: convert imgs into pimgs + g := gif.GIF{ + Image: make([]*image.Paletted, len(imgs)), + Delay: make([]int, len(imgs)), + } + b := make([]byte, 0, 1024) + for i, img := range imgs { + buf := bytes.NewBuffer(b) + if err = gif.Encode(buf, img, &gif.Options{NumColors: 256}); err != nil { + return err + } + gimg, err := gif.DecodeAll(buf) + if err != nil { + return err + } + g.Delay[i] = 0 + g.Image[i] = gimg.Image[0] + } - return gif.EncodeAll(f, &gif.GIF{Image:pimgs}) + return gif.EncodeAll(f, &g) }