a3web/maptool-go/main.go

92 lines
2.0 KiB
Go

package main
import (
"flag"
"fmt"
"image"
"image/color"
"image/jpeg"
"log"
"os"
"strings"
"sync"
"github.com/disintegration/imaging"
)
var (
origMap string
maxLevel int
)
func init() {
flag.StringVar(&origMap, "map", "Enoch.png", "original map file")
flag.IntVar(&maxLevel, "level", 3, "resize level")
}
func main() {
flag.Parse()
origImgFile, err := os.Open(origMap)
if err != nil {
panic(err)
}
defer origImgFile.Close()
config, format, err := image.DecodeConfig(origImgFile)
if err != nil {
panic(err)
}
fmt.Println("Width:", config.Width, "Height:", config.Height, "Format:", format)
origImgFile.Seek(0, 0)
img, _, err := image.Decode(origImgFile)
if err != nil {
panic(err)
}
//////////////////////
width := config.Width
dirName := strings.Split(origMap, ".")[0]
os.Mkdir(dirName, os.ModeDir)
for i := 3; i > 0; i-- {
log.Println(i)
corpImage(img, width, i, dirName)
width = width / 2
img = imaging.Resize(img, width, 0, imaging.Lanczos)
}
}
type subImager interface {
SubImage(r image.Rectangle) image.Image
}
func corpImage(img image.Image, width int, level int, dirname string) {
lveledirname := fmt.Sprintf("%s/%d", dirname, level)
os.Mkdir(lveledirname, os.ModeDir)
var wg sync.WaitGroup
if img, ok := img.(subImager); ok {
for i := 0; i < width; i = i + 1000 {
for j := 0; j < width; j = j + 1000 {
wg.Add(1)
go func(wg *sync.WaitGroup, i, j int, img subImager) {
rect := image.Rect(i, j, i+1000, j+1000)
imgOut := img.SubImage(rect)
imgOut = imaging.Paste(imaging.New(1000, 1000, color.NRGBA{0, 0, 0, 0}), imgOut, image.Pt(0, 0))
fileName := fmt.Sprintf("%s/%d/x%d_y%d.jpg", dirname, level, i/1000, j/1000)
fileOut, err := os.Create(fileName)
if err != nil {
panic(err)
}
jpeg.Encode(fileOut, imgOut, &jpeg.Options{Quality: 85})
fileOut.Close()
wg.Done()
}(&wg, i, j, img)
}
}
} else {
log.Fatalln("Cannot take a SubImage")
}
wg.Wait()
}