Skip to content

Commit

Permalink
goroutine
Browse files Browse the repository at this point in the history
  • Loading branch information
fluffy-melli committed Dec 27, 2024
1 parent c3bcd40 commit f7cccba
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 16 deletions.
56 changes: 41 additions & 15 deletions render/gifs.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,55 @@ import (
"image"
"image/color"
"image/gif"
"sort"
"sync"
)

func GIF(urls []string, delay int) (*bytes.Buffer, error) {
var images []*image.Paletted
var delays []int
for _, url := range urls {
img, err := LoadImageFromURL(url)
if err != nil {
return nil, err
func GIF(urls []string, delay int, low bool) (*bytes.Buffer, error) {
var mu sync.Mutex
var wg sync.WaitGroup
var images map[int]*image.Paletted = make(map[int]*image.Paletted)
sem := make(chan struct{}, 5)
for i, url := range urls {
if low && (i+1)%3 != 0 { // | 15min
continue
}
palette := Palette(img)
palettedImage := image.NewPaletted(img.Bounds(), palette)
for y := 0; y < palettedImage.Bounds().Dy(); y++ {
for x := 0; x < palettedImage.Bounds().Dx(); x++ {
palettedImage.Set(x, y, img.At(x, y))
wg.Add(1)
sem <- struct{}{}
go func(i int, url string) {
defer wg.Done()
defer func() { <-sem }()
img, err := LoadImageFromURL(url)
if err != nil {
return
}
}
images = append(images, palettedImage)
palette := Palette(img)
palettedImage := image.NewPaletted(img.Bounds(), palette)
for y := 0; y < palettedImage.Bounds().Dy(); y++ {
for x := 0; x < palettedImage.Bounds().Dx(); x++ {
palettedImage.Set(x, y, img.At(x, y))
}
}
mu.Lock()
images[i] = palettedImage
mu.Unlock()
}(i, url)
}
wg.Wait()
var keys []int
var delays []int
var result []*image.Paletted
for key := range images {
keys = append(keys, key)
}
sort.Ints(keys)
for _, key := range keys {
result = append(result, images[key])
delays = append(delays, delay)
}
var buf bytes.Buffer
err := gif.EncodeAll(&buf, &gif.GIF{
Image: images,
Image: result,
Delay: delays,
})
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion test/module_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ func Test(t *testing.T) {
if err != nil {
log.Fatalln(err)
}
gif, err := render.GIF(urls, 5)
gif, err := render.GIF(urls, 10, true)
if err != nil {
log.Fatalln(err)
}
Expand Down
Binary file modified test/test.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit f7cccba

Please sign in to comment.