mbaranowski
3/26/2013 - 2:20 PM

Slice The Images

Slice The Images

package main

import (
  "fmt"
	"image"
	"image/png"
	"os"
	"log"
	"strconv"
)

func CopySubImage(srcImg* image.Image, sp image.Point, dstImg* image.RGBA, dp image.Point, size image.Point) error {

	for y := 0; y < size.Y; y+=1 {
		for x := 0; x < size.X; x+=1 {
			//dstImg.Pix[ dstImg.PixOffset(dp.X+x,dp.Y+y) ] = srcImg.Pix[ srcImg.PixOffset(sp.X+x,sp.Y+y) ];
			dstImg.Set(dp.X+x,dp.Y+y, (*srcImg).At(sp.X+x,sp.Y+y) )
		}
	}

	return nil
}

func main() {
	
	if len(os.Args) < 6 {
		fmt.Printf("usage: %s <filename> <left> <top> <right> <bottom>\n", os.Args[0])
		return
	}
	
	filename := os.Args[1]
	edgeInsets := os.Args[2:6]
	
	file, err := os.Open(filename)
	if err != nil {
		log.Fatal(err)
		return
	}
	defer file.Close()

	
	outFilename := "out_" + filename
	if len(os.Args) > 6 {
		outFilename = os.Args[6]
	}
	
	outputFile, err := os.Create(outFilename)
	if err != nil {
		log.Fatal(err)
		return
	}
	defer outputFile.Close()

	inputImage, err := png.Decode(file)
	if err != nil {
		log.Fatal(err)
	}


	var left, top, right, bottom  int;
	ptrs := []*int { &left, &top, &right, &bottom };
	for i := range ptrs {
		intVal, err := strconv.Atoi(edgeInsets[i])
		if err != nil {
			fmt.Printf("invalid edge inset value: %s", edgeInsets[i])
			log.Fatal(err)
		} 
		*ptrs[i] = intVal
	}

	inputBounds := inputImage.Bounds()
	inputWidth := inputBounds.Size().X
	inputHeight := inputBounds.Size().Y

	outputImage  := image.NewRGBA( image.Rect(0,0,left+right+1,top+bottom+1) )

	CopySubImage(&inputImage,  image.Point{0,0},
		     outputImage, image.Point{0,0}, image.Point{left+1,top+1});

	CopySubImage(&inputImage , image.Point{inputWidth-right,0},
		     outputImage, image.Point{left+1,0}, image.Point{right,top+1});

	CopySubImage(&inputImage,  image.Point{0,inputHeight-bottom},
		     outputImage, image.Point{0,top+1}, image.Point{left+1,bottom});

	CopySubImage(&inputImage,  image.Point{inputWidth-right,inputHeight-bottom},
		     outputImage, image.Point{left+1,top+1}, image.Point{right,bottom});
	
		
	encErr := png.Encode(outputFile, outputImage)
	if encErr != nil {
		log.Fatal(encErr)
	}

	fmt.Printf("done, output:\"%s\", bounds:%v\n", outFilename, outputImage.Bounds().Size())
}