首頁 > 後端開發 > Golang > 主體

golang 圖片旋轉

王林
發布: 2023-05-19 09:16:36
原創
806 人瀏覽過

Golang是一門快速發展的程式語言,常用於大規模網路應用程式和雲端運算。在影像處理方面,Golang提供了簡單易用且高效的API,這使得圖片旋轉變得十分簡單。

下面,我們將示範如何使用Golang實現圖片旋轉。假設我們有一張名為「image.jpg」的JPEG圖片需要被旋轉90度,接下來我們將使用Golang來完成這個任務。

首先,我們需要匯入Golang自帶的「image」和「image/jpeg」函式庫。

import (
    "image"
    "image/jpeg"
)
登入後複製

接下來,我們需要打開並解碼圖像檔案。

path := "image.jpg"
file, err := os.Open(path)
if err != nil {
    //处理错误
}
defer file.Close()

img, err := jpeg.Decode(file)
if err != nil {
    //处理错误
}
登入後複製

現在,我們可以透過對影像矩陣進行旋轉來實現旋轉功能。在Golang中,可以透過「draw」套件來實現這個目標。我們需要先建立一個新的圖像,然後將原始圖像複製到這個新圖像上並旋轉它。

newImg := image.NewRGBA(image.Rect(0, 0, img.Bounds().Dy(), img.Bounds().Dx()))

//拷贝原图像到新图像
draw.Draw(newImg, newImg.Bounds(), img, img.Bounds().Min, draw.Src)

//旋转新图像
rotatedImg := imaging.Rotate(newImg, 90, color.Transparent)
登入後複製

最後,我們需要將旋轉後的圖像儲存到檔案中。我們將旋轉後的圖片儲存為「rotatedImage.jpg」。

outputFile, err := os.Create("rotatedImage.jpg")
if err != nil {
    //处理错误
}
defer outputFile.Close()

//将旋转后的图像保存到文件中
jpeg.Encode(outputFile, rotatedImg, nil)
登入後複製

完整的範例程式碼:

package main

import (
    "image"
    "image/color"
    "image/draw"
    "image/jpeg"
    "os"

    "github.com/disintegration/imaging"
)

func main() {
    path := "image.jpg"
    file, err := os.Open(path)
    if err != nil {
        //处理错误
    }
    defer file.Close()

    img, err := jpeg.Decode(file)
    if err != nil {
        //处理错误
    }

    newImg := image.NewRGBA(image.Rect(0, 0, img.Bounds().Dy(), img.Bounds().Dx()))

    //拷贝原图像到新图像
    draw.Draw(newImg, newImg.Bounds(), img, img.Bounds().Min, draw.Src)

    //旋转新图像
    rotatedImg := imaging.Rotate(newImg, 90, color.Transparent)

    outputFile, err := os.Create("rotatedImage.jpg")
    if err != nil {
        //处理错误
    }
    defer outputFile.Close()

    //将旋转后的图像保存到文件中
    jpeg.Encode(outputFile, rotatedImg, nil)
}
登入後複製

在執行上述程式碼後,我們將得到一張90度旋轉的圖片,並儲存為「rotatedImage.jpg」。

總結:

在本文中,我們展示如何使用Golang實現圖片旋轉。我們使用了Golang自帶的“image”和“image/jpeg”庫,並使用“draw”套件來旋轉圖像。透過這個簡單的範例,我們能更了解Golang在影像處理方面的強大能力。

以上是golang 圖片旋轉的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!