Skip to content

Instantly share code, notes, and snippets.

@s-aska s-aska/thumbnail.go
Created Oct 4, 2017

Embed
What would you like to do?
サムネイル生成くん
package main
import (
"fmt"
"image"
"image/jpeg"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"github.com/nfnt/resize"
)
func main() {
inputDir := os.Args[1]
outputDir := os.Args[2]
fmt.Printf("src: %s\n", inputDir)
fmt.Printf("dst: %s\n", outputDir)
qualities := []int{60, 80, 90, 100}
widths := []uint{600, 700, 800, 900, 1000}
files, err := ioutil.ReadDir(inputDir)
if err != nil {
panic(err)
}
for _, file := range files {
if !strings.HasSuffix(file.Name(), ".jpg") {
continue
}
input := path.Join(inputDir, file.Name())
file, err := os.Open(input)
if err != nil {
panic(err)
}
img, err := jpeg.Decode(file)
if err != nil {
panic(err)
}
file.Close()
id := strings.TrimSuffix(filepath.Base(file.Name()), path.Ext(file.Name()))
fmt.Printf(" convert %s\n", file.Name())
for _, quality := range qualities {
Thumbnail(img, outputDir, id, quality, 1000)
}
for _, width := range widths {
Thumbnail(img, outputDir, id, 80, width)
}
}
}
// Thumbnail 生成
func Thumbnail(input image.Image, outputDir string, id string, quality int, width uint) {
thumbnail := resize.Thumbnail(width, width, input, resize.Lanczos3)
out, err := os.Create(path.Join(outputDir, fmt.Sprintf("%s_q%dw%d.jpg", id, quality, width)))
if err != nil {
panic(err)
}
defer out.Close()
jpeg.Encode(out, thumbnail, &jpeg.Options{Quality: quality})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.