ZBLOG

golang 图片等比缩放

在 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)
}

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=244

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?