GO 图像操作-缩放
大约 1 分钟
GoLang 图像处理 - 缩放
源码
package img
import (
"image"
"image/color"
"math"
)
// Resize 缩放图像
func Resize(newSize image.Point, src image.Image) image.Image {
srcScale := src.Bounds().Max
println(srcScale.X, srcScale.Y)
rateX, rateY := float64(srcScale.X)/float64(newSize.X), float64(srcScale.Y)/float64(newSize.Y)
dst := image.NewRGBA(image.Rect(0, 0, newSize.X, newSize.Y))
for x := 0; x < newSize.X; x++ {
for y := 0; y < newSize.Y; y++ {
pX, pY := (float64(x)+0.5)*rateX-0.5, (float64(y)+0.5)*rateY-0.5
x1, y1 := math.Floor(pX), math.Floor(pY)
x2, y2 := math.Min(x1+1, float64(srcScale.X-1)), math.Min(y1+1, float64(srcScale.Y-1))
//R = (x2 - x) * f(X1) + (x - x1) * f(x2)
r1 := Add(Mul(src.At(int(x1), int(y1)), x2-pX), Mul(src.At(int(x2), int(y1)), pX-x1))
r2 := Add(Mul(src.At(int(x1), int(y2)), x2-pX), Mul(src.At(int(x2), int(y2)), pX-x1))
r3 := Add(Mul(r1, y2-pY), Mul(r2, pY-y1))
dst.Set(x, y, r3)
}
}
return dst
}
// Mul 颜色(RGBA)乘以指定常数
func Mul(src color.Color, num float64) color.Color {
r, g, b, a := src.RGBA()
return color.RGBA64{
R: uint16(float64(r) * num),
G: uint16(float64(g) * num),
B: uint16(float64(b) * num),
A: uint16(float64(a) * num)}
}
// Add 颜色(RGBA)相加
func Add(a, b color.Color) color.Color {
r1, g1, b1, a1 := a.RGBA()
r2, g2, b2, a2 := b.RGBA()
return color.RGBA64{
R: uint16(r1 + r2),
G: uint16(g1 + g2),
B: uint16(b1 + b2),
A: uint16(a1 + a2),
}
}
使用例
func main() {
file, err := os.Open("384.jpg")
if err != nil {
log.Fatalf("failed to open image: %v", err)
}
src, err := jpeg.Decode(file)
if err != nil {
log.Fatalf("failed to decode image: %v", err)
}
dst := img.Resize(image.Pt(256, 256), src)
dest, _ := os.Create("dest.png")
png.Encode(dest, dst)
}