在 Golang 中,可以使用 image 和 draw 包来完成图片等比缩放。
首先,需要加载原始图片。假设要对名为 “test.jpg” 的图片进行等比缩放,代码如下:
import (
"image"
"os"
)
func main() {
file, err := os.Open("test.jpg")
if err != nil {
panic(err)
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
panic(err)
}
// 处理 img ...
}
接着,可以根据目标宽度和高度计算缩放比例,并创建一个新的图像对象:
import (
"image"
"image/draw"
"image/jpeg"
"os"
)
func main() {
file, err := os.Open("test.jpg")
if err != nil {
panic(err)
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
panic(err)
}
// 计算缩放比例
width := 300 // 目标宽度
height := 200 // 目标高度
bounds := img.Bounds()
wRatio := float64(bounds.Dx()) / float64(width)
hRatio := float64(bounds.Dy()) / float64(height)
ratio := wRatio
if hRatio > wRatio {
ratio = hRatio
}
// 创建新的图像对象
newWidth := int(float64(bounds.Dx()) / ratio)
newHeight := int(float64(bounds.Dy()) / ratio)
newImg := image.NewRGBA(image.Rect(0, 0, newWidth, newHeight))
// 将原始图像绘制到新的图像对象中
draw.CatmullRom.Scale(newImg, newImg.Bounds(), img, bounds, draw.Over, nil)
// 将新的图像保存到文件中
outFile, err := os.Create("test_resized.jpg")
if err != nil {
panic(err)
}
defer outFile.Close()
jpeg.Encode(outFile, newImg, nil)
}
在上面的代码中,使用 CatmullRom 算法来进行缩放操作,并将新的图像保存到 “test_resized.jpg” 文件中。
完整代码如下:
package main
import (
"image"
"image/draw"
"image/jpeg"
"os"
)
func main() {
file, err := os.Open("test.jpg")
if err != nil {
panic(err)
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
panic(err)
}
// 计算缩放比例
width := 300 // 目标宽度
height := 200 // 目标高度
bounds := img.Bounds()
wRatio := float64(bounds.Dx()) / float64(width)
hRatio := float64(bounds.Dy()) / float64(height)
ratio := wRatio
if hRatio > wRatio {
ratio = hRatio
}
// 创建新的图像对象
newWidth := int(float64(bounds.Dx()) / ratio)
newHeight := int(float64(bounds.Dy()) / ratio)
newImg := image.NewRGBA(image.Rect(0, 0, newWidth, newHeight))
// 将原始图像绘制到新的图像对象中
draw.CatmullRom.Scale(newImg, newImg.Bounds(), img, bounds, draw.Over, nil)
// 将新的图像保存到文件中
outFile, err := os.Create("test_resized.jpg")
if err != nil {
panic(err)
}
defer outFile.Close()
jpeg.Encode(outFile, newImg, nil)
}