package images import ( "bytes" "image" "image/draw" "image/jpeg" "io/ioutil" "log" "os" "path/filepath" "strings" "github.com/anthonynsimon/bild/transform" ) // SupportedTypes are supported image extensions/formats. var SupportedTypes = []string{ ".jpeg", ".jpg", ".png", // ".gif", } // IsSupported is a simple helper that checks if an extension is supported. func IsSupported(extension string) bool { for _, supported := range SupportedTypes { if extension == supported { return true } } return false } func thumbnailGenerator(work <-chan string) { for filename := range work { thumbname := strings.TrimSuffix(filename, filepath.Ext(filename)) + "_th" + filepath.Ext(filename) if _, err := os.Stat("storage/" + thumbname); os.IsExist(err) { log.Printf( "Thumbnail %s already exists, skipping\n", "storage/"+thumbname, ) continue } log.Printf( "Thumbnailing %s to %s\n", "storage/"+filename, "storage/"+thumbname, ) srcFile, err := os.Open("storage/" + filename) if err != nil { log.Printf("could not open file: %s\n", err) continue } data, err := ioutil.ReadAll(srcFile) if err != nil { log.Printf("could not read file: %s\n", err) continue } srcFile.Close() img, _, err := image.Decode(bytes.NewReader(data)) if err != nil { log.Printf("could not decode image: %s\n", err) continue } srcW := float64(img.Bounds().Dx()) srcH := float64(img.Bounds().Dy()) dstW, dstH := 160, 120 if srcW > srcH { ratio := srcH / srcW dstH = int(float64(dstW) * ratio) } else { ratio := srcW / srcH dstW = int(float64(dstH) * ratio) } resized := transform.Resize(img, dstW, dstH, transform.Lanczos) thumbImg := image.NewRGBA(image.Rect(0, 0, 160, 120)) draw.Draw( thumbImg, image.Rect(80-(dstW/2), 60-(dstH/2), 160, 120), resized, image.Point{}, draw.Src, ) dstFile, err := os.Create("storage/" + thumbname) if err != nil { log.Printf("could not create image: %s\n", err) continue } err = jpeg.Encode(dstFile, thumbImg, nil) if err != nil { log.Printf("could not encode image: %s\n", err) continue } dstFile.Close() } }