Skip to content

Instantly share code, notes, and snippets.

@supercaracal
Last active January 12, 2026 03:28
Show Gist options
  • Select an option

  • Save supercaracal/67a37bc3c4e140fb84144f6e84226a46 to your computer and use it in GitHub Desktop.

Select an option

Save supercaracal/67a37bc3c4e140fb84144f6e84226a46 to your computer and use it in GitHub Desktop.
a naive webp-to-jpeg converter
package main
import (
"flag"
"fmt"
"image"
"image/jpeg"
"log"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
_ "golang.org/x/image/webp"
)
func main() {
srcDirPath := ""
dryRun := false
flag.StringVar(&srcDirPath, "src", "", "source directory path")
flag.BoolVar(&dryRun, "dry-run", false, "whether dry-run or not")
flag.Parse()
if srcDirPath == "" {
log.Fatal("empty source directory path given")
}
if v, err := filepath.Abs(srcDirPath); err != nil {
log.Fatal(err)
} else {
srcDirPath = v
}
destDirPath := filepath.Join(srcDirPath, "converted")
if err := os.Mkdir(destDirPath, 0755); err != nil && !os.IsExist(err) {
log.Fatal(err)
}
files, err := os.ReadDir(srcDirPath)
if err != nil {
log.Fatal(err)
}
concurrency := make(chan struct{}, runtime.GOMAXPROCS(0))
defer close(concurrency)
var wg sync.WaitGroup
for _, file := range files {
if file.IsDir() || !file.Type().IsRegular() {
continue
}
srcFileName := file.Name()
srcFilePath := filepath.Join(srcDirPath, srcFileName)
destFileName := fmt.Sprintf("%s.jpg", strings.TrimSuffix(srcFileName, filepath.Ext(srcFileName)))
destFilePath := filepath.Join(destDirPath, destFileName)
log.Printf("%s -> %s", srcFilePath, destFilePath)
if dryRun {
continue
}
concurrency <- struct{}{}
wg.Go(func() {
if err := convert(srcFilePath, destFilePath); err != nil {
log.Print(err)
}
<-concurrency
})
}
wg.Wait()
}
func convert(srcFilePath, destFilePath string) error {
srcFp, err := os.Open(srcFilePath)
if err != nil {
return err
}
defer srcFp.Close()
img, format, err := image.Decode(srcFp)
if err != nil {
return err
}
if format != "webp" {
return fmt.Errorf("unexpected file format: %s", format)
}
destFp, err := os.OpenFile(destFilePath, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
return err
}
defer destFp.Close()
if err := jpeg.Encode(destFp, img, &jpeg.Options{Quality: jpeg.DefaultQuality}); err != nil {
return err
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment