Source

pdb / images / prep.go

Full commit
package main

import (
	"image"
	"image/png"
	"image/jpeg"
	"log"
	"os"
	"flag"
	"fmt"
	"strings"
	"strconv"
)

var _ = fmt.Printf

var pic string
var out string

func openImage(pic string) (m image.Image) {
	f, err := os.Open(pic, os.O_RDONLY, 0666)
	if err != nil {
		log.Exit(err)
	}
	if strings.HasSuffix(pic, "png") {
		m, err = png.Decode(f)
	} else {
		if strings.HasSuffix(pic, "jpeg") || strings.HasSuffix(pic, "jpg") {
			m, err = jpeg.Decode(f)
		} else {
			log.Exit("unkown file format")
		}
	}
	if err != nil{
		log.Exit(err)
	}
	return m
}

//note: -resize is -scale + some smoothing, so maybe we'll want -resize
func degrade(inputfile string, counter int, width int, height int) os.Error {
	suffixes := []string{".jpg", ".jpeg", ".png"}
	var suffix string
	for _, suffix = range suffixes {
		if strings.Index(inputfile,	suffix) != -1 {
			break
		}
	}
	outputfile := strings.Replace(inputfile, suffix, "-" + fmt.Sprint(counter) + suffix, 1)
	tmpfile := "/tmp/foo" + suffix
	w := width / (3 * counter)
	h := height / (3 * counter)
	geometry := fmt.Sprint(w) + "x" + fmt.Sprint(h)

	if counter == 1 {
		var args []string = make([]string, 3)
		args[0] = "/bin/cp"
		args[1] = inputfile
		args[2] = outputfile
		fds := []*os.File{os.Stdin, os.Stdout, os.Stderr}
		pid, err := os.ForkExec(args[0], args, os.Environ(), "", fds)
		if err != nil {
			return err
		}
		_, err = os.Wait(pid, os.WSTOPPED)
		if err != nil {
			return err
		}
		return nil
	}

	var args []string = make([]string, 5)
	args[0] = "/usr/bin/convert"
	args[1] = inputfile
	args[2] = "-scale"
	args[3] = geometry
	args[4] = tmpfile
	fds := []*os.File{os.Stdin, os.Stdout, os.Stderr}
	pid, err := os.ForkExec(args[0], args, os.Environ(), "", fds)
	if err != nil {
		return err
	}
	_, err = os.Wait(pid, os.WSTOPPED)
	if err != nil {
		return err
	}

	geometry = fmt.Sprint(width) + "x" + fmt.Sprint(height)
	args[1] = tmpfile
	args[2] = "-scale"
	args[3] = geometry
	args[4] = outputfile
	pid, err = os.ForkExec(args[0], args, os.Environ(), "", fds)
	if err != nil {
		return err
	}
	_, err = os.Wait(pid, os.WSTOPPED)
	if err != nil {
		return err
	}
	return nil
}
func usage() {
	fmt.Fprintf(os.Stderr, "usage:\t prep image [n] \n");
	os.Exit(2);
}

func main() {
	flag.Usage = usage
	flag.Parse()
	args := flag.Args()

	var n int
	var err os.Error
	switch flag.NArg() {
	case 1:
		n = 6
	case 2:
		n, err = strconv.Atoi(args[1])
		if err != nil {
			os.Exit(1)
		}
	default:
		usage()
	}

	pic = args[0]
	// lazy testing for image format
	im := openImage(pic)

	for i:=0; i<n; i++ {
		degrade(pic, i+1, im.Bounds().Dx(), im.Bounds().Dy())
	}

}