」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 Go 中連接影像?

如何在 Go 中連接影像?

發佈於2024-11-09
瀏覽:498

How to Concatenate Images in Go?

Go 中連接圖像:綜合指南

在 Go 中,由於其強大的圖像庫,操作圖像變得輕而易舉。但是,如果您想將多個圖像合併到一張大畫布中,事情可能會變得混亂。這是一個像專業人士一樣處理此任務的分步指南。

載入圖片

首先,載入您想要連接的映像。這是執行此操作的程式碼片段:

// Open the first image
imgFile1, err := os.Open("test1.jpg")
if err != nil {
    fmt.Println(err)
}
// Decode the image
img1, _, err := image.Decode(imgFile1)
if err != nil {
    fmt.Println(err)
}

// Open the second image
imgFile2, err := os.Open("test2.jpg")
if err != nil {
    fmt.Println(err)
}
// Decode the image
img2, _, err := image.Decode(imgFile2)
if err != nil {
    fmt.Println(err)
}

創建新圖像

接下來,讓我們創建一個寬敞的新圖像來容納兩個已載入的圖像。透過新增兩個影像的寬度來決定此新畫布的尺寸:

r := image.Rectangle{image.Point{0, 0}, img1.Bounds().Dx()   img2.Bounds().Dx(), img1.Bounds().Dy()}
rgba := image.NewRGBA(r)

繪製圖像

現在是有趣的部分:在這個新畫布中組裝圖像。確定要放置第二個影像的位置,然後將兩個影像都繪製到畫布上:

// Starting point of the second image (bottom left)
sp2 := image.Point{img1.Bounds().Dx(), 0}
// Rectangle for the second image
r2 := image.Rectangle{sp2, sp2.Add(img2.Bounds().Size())}

// Draw the first image
draw.Draw(rgba, img1.Bounds(), img1, image.Point{0, 0}, draw.Src)
// Draw the second image
draw.Draw(rgba, r2, img2, image.Point{0, 0}, draw.Src)

保存結果

最後,讓我們永久化這個串聯將其另存為新圖像檔案來製作傑作:

out, err := os.Create("./output.jpg")
if err != nil {
    fmt.Println(err)
}

var opt jpeg.Options
opt.Quality = 80

jpeg.Encode(out, rgba, &opt)

就是這樣!您已成功將多個影像合併為一個有凝聚力的整體。繼續前進,征服圖像處理的世界。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3