Created
September 20, 2020 09:55
-
-
Save Oppodelldog/920fae560fb50a282e2a02b6864ea514 to your computer and use it in GitHub Desktop.
Resize Icon for unity
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 ( | |
"bytes" | |
"fmt" | |
"github.com/nfnt/resize" | |
"image" | |
"image/png" | |
"io" | |
"io/ioutil" | |
"os" | |
"path" | |
"strings" | |
) | |
const outputPath = "out" | |
const baseName = "icon" | |
const baseImage = "icon-512.png" | |
type target struct { | |
n string | |
w uint | |
h uint | |
f bool | |
e encodeFunc | |
} | |
type encodeFunc func(io.Writer, image.Image) error | |
var icons = []target{ | |
{n: "%s-legacy-ldpi-%vx%v.png", w: 36, h: 36, e: png.Encode}, | |
{n: "%s-legacy-mdpi-%vx%v.png", w: 48, h: 48, e: png.Encode}, | |
{n: "%s-legacy-hdpi-%vx%v.png", w: 72, h: 72, e: png.Encode}, | |
{n: "%s-legacy-xhdpi-%vx%v.png", w: 96, h: 96, e: png.Encode}, | |
{n: "%s-legacy-xxhdpi-%vx%v.png", w: 144, h: 144, e: png.Encode}, | |
{n: "%s-legacy-xxhdpi-%vx%v.png", w: 192, h: 192, e: png.Encode}, | |
{n: "%s-ldpi-%vx%v.png", w: 81, h: 81, e: png.Encode}, | |
{n: "%s-mdpi-%vx%v.png", w: 108, h: 108, e: png.Encode}, | |
{n: "%s-hdpi-%vx%v.png", w: 162, h: 162, e: png.Encode}, | |
{n: "%s-xhdpi-%vx%v.png", w: 216, h: 216, e: png.Encode}, | |
{n: "%s-xxhdpi-%vx%v.png", w: 324, h: 324, e: png.Encode}, | |
{n: "%s-xxhdpi-%vx%v.png", w: 432, h: 432, e: png.Encode}, | |
} | |
func main() { | |
must(os.RemoveAll(outputPath)) | |
must(os.MkdirAll(outputPath, 0777)) | |
img := getSourceImage() | |
for _, target := range append([]target{}, icons...) { | |
newImage := resize.Resize(target.w, target.h, img, resize.Lanczos3) | |
f, err := os.Create(path.Join(outputPath, getFilename(target))) | |
panicOnError(err) | |
must(target.e(f, newImage)) | |
must(f.Close()) | |
} | |
} | |
func getSourceImage() image.Image { | |
b, err := ioutil.ReadFile(baseImage) | |
panicOnError(err) | |
img, err := png.Decode(bytes.NewReader(b)) | |
panicOnError(err) | |
return img | |
} | |
func getFilename(target target) string { | |
var filename = target.n | |
if strings.Contains(target.n, "%v") { | |
filename = fmt.Sprintf(target.n, baseName, target.w, target.h) | |
} | |
return filename | |
} | |
func must(err error) { | |
panicOnError(err) | |
} | |
func panicOnError(err error) { | |
if err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment