Skip to content

Instantly share code, notes, and snippets.

Created October 10, 2014 05:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/8f328359f07f6c5d142e to your computer and use it in GitHub Desktop.
Save anonymous/8f328359f07f6c5d142e to your computer and use it in GitHub Desktop.
graphic magic image transform
func resize(context *core.Context, imageWidth int, imageHeight int, quality string, destination string) error {
reqWidth, reqHeight := context.Width, context.Height
finalWidth, finalHeight := imageWidth, imageHeight
var resizeArgument, extendArgument string
if context.Width == 0 {
resizeArgument = strconv.Itoa(finalWidth) + "x" + strconv.Itoa(finalHeight)
extendArgument = "+0+0"
} else {
finalWidth, finalHeight = reqWidth, reqHeight
widthRatio := float64(reqWidth) / float64(imageWidth)
heightRatio := float64(reqHeight) / float64(imageHeight)
ratio := widthRatio
if context.Preserve {
if heightRatio < widthRatio {
ratio = heightRatio
}
} else {
if heightRatio > widthRatio {
ratio = heightRatio
}
}
finalWidth = int(float64(imageWidth)*ratio) + 1
finalHeight = int(float64(imageHeight)*ratio) + 1
resizeArgument = strconv.Itoa(reqWidth) + "x" + strconv.Itoa(reqHeight)
extendArgument = resizeArgument
if context.Anchored {
ax := float64(context.AnchorX) / float64(imageWidth) * float64(finalWidth-reqWidth)
ay := float64(context.AnchorY) / float64(imageHeight) * float64(finalHeight-reqHeight)
extendArgument += "+" + strconv.Itoa(int(ax)) + "+" + strconv.Itoa(int(ay))
} else {
extendArgument += "+" + strconv.Itoa(int(float64((finalWidth-reqWidth)/2.0))) + "+" + strconv.Itoa(int(float64((finalHeight-reqHeight)/2.0)))
}
}
args := []string{
"convert",
"-size", resizeArgument,
"-resize", strconv.Itoa(finalWidth) + "x" + strconv.Itoa(finalHeight),
"-extent", extendArgument,
"-quality", quality,
"-strip",
"-interlace", "line",
context.OriginalPath,
destination,
}
return exec.Command("gm", args...).Run()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment