Created
December 30, 2018 09:30
-
-
Save dhrubabasu/27582e3069f4c31cf366acbb46fdad86 to your computer and use it in GitHub Desktop.
Optimizes images using pingo/jpegtran
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"github.com/h2non/filetype" | |
"io/ioutil" | |
"os" | |
"os/exec" | |
"path/filepath" | |
"strconv" | |
"strings" | |
) | |
func main() { | |
var files []string | |
folder := os.Args[1] | |
filepath.Walk(folder, func(path string, info os.FileInfo, err error) error { | |
if info.IsDir() { | |
return nil | |
} | |
files = append(files, path) | |
return nil | |
}) | |
fileList, _ := os.Create("file_list.args") | |
workers := 5 | |
sem := make(chan bool, workers) | |
for i, file := range files { | |
sem <- true | |
go func(i int, file string) { | |
defer func() { <-sem }() | |
buf, _ := ioutil.ReadFile(file) | |
kind, unknown := filetype.Match(buf) | |
if unknown != nil { | |
return | |
} | |
if filetype.IsImage(buf) { | |
fmt.Fprintln(fileList, file) | |
if (kind.MIME.Value == "image/png") { | |
os.MkdirAll("pimgs", 0777) | |
os.Symlink(file, "pimgs/" + strconv.Itoa(i) + filepath.Ext(file)) | |
} | |
if (kind.MIME.Value == "image/jpeg") { | |
cmd := exec.Command("exiftool" , "-p", "'$colorcomponents'", file) | |
out, _ := cmd.CombinedOutput() | |
if strings.Trim(strings.TrimSpace(string(out)),`'`) == "1" { | |
os.MkdirAll("pimgs", 0777) | |
os.Symlink(file, "pimgs/" + strconv.Itoa(i) + filepath.Ext(file)) | |
} else { | |
cmd := exec.Command("jpegtran", "-copy", "none", "-optimize", "-progressive", "-outfile", file, file) | |
_, err := cmd.CombinedOutput() | |
if err != nil { | |
fmt.Println(err) | |
} | |
} | |
} | |
} | |
}(i, file) | |
} | |
for i := 0; i < cap(sem); i++ { | |
sem <- true | |
} | |
if _, err := os.Stat("pimgs/"); !os.IsNotExist(err) { | |
cmd := exec.Command("bash", "-c", "wine ~/go/src/optimize/pingo.exe pimgs -s8") | |
out, _ := cmd.CombinedOutput() | |
fmt.Print(string(out)) | |
} | |
out, _ := exec.Command("exiftool", "-overwrite_original", "-all=", "-@", "file_list.args" ).Output() | |
fmt.Print(string(out)) | |
os.RemoveAll("pimgs") | |
os.RemoveAll("file_list.args") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment