3 回答

TA貢獻1951條經(jīng)驗 獲得超3個贊
創(chuàng)建一個新的空圖像 (NewRGBA),其邊界足夠大以容納兩個圖像。然后使用該Draw方法在這個新的大圖像的適當部分繪制每個圖像。
以下是代碼步驟。
加載兩個圖像。
imgFile1, err := os.Open("test1.jpg")
if err != nil {
fmt.Println(err)
}
imgFile2, err := os.Open("test2.jpg")
if err != nil {
fmt.Println(err)
}
img1, _, err := image.Decode(imgFile1)
if err != nil {
fmt.Println(err)
}
img2, _, err := image.Decode(imgFile2)
if err != nil {
fmt.Println(err)
}
讓我們在第一個圖像的右側(cè)繪制第二個圖像。所以它的起點應(yīng)該是第一個圖像的寬度在(w, 0)哪里w。第一個圖像的右下角將是第二個圖像的左下角。
//starting position of the second image (bottom left)
sp2 := image.Point{img1.Bounds().Dx(), 0}
它應(yīng)該在一個足以容納它的矩形中。
//new rectangle for the second image
r2 := image.Rectangle{sp2, sp2.Add(img2.Bounds().Size())}
現(xiàn)在創(chuàng)建一個大矩形,其寬度足以容納兩個圖像。
//rectangle for the big image
r := image.Rectangle{image.Point{0, 0}, r2.Max}
注意此大圖像將具有第二個圖像的高度。如果第一張圖像更高,它將被裁剪。
創(chuàng)建一個新圖像。
rgba := image.NewRGBA(r)
現(xiàn)在您可以將這兩個圖像繪制到這個新圖像中
draw.Draw(rgba, img1.Bounds(), img1, image.Point{0, 0}, draw.Src)
draw.Draw(rgba, r2, img2, image.Point{0, 0}, draw.Src)
由于我們在r2第一張圖片的右側(cè)創(chuàng)建了它,因此第二張圖片將被繪制到右側(cè)。
最后就可以導出了。
out, err := os.Create("./output.jpg")
if err != nil {
fmt.Println(err)
}
var opt jpeg.Options
opt.Quality = 80
jpeg.Encode(out, rgba, &opt)

TA貢獻1909條經(jīng)驗 獲得超7個贊
如果你把一些東西變成函數(shù)并創(chuàng)建一個結(jié)構(gòu)來理解每個像素,你的生活會容易得多。
// Create a struct to deal with pixel
type Pixel struct {
Point image.Point
Color color.Color
}
// Keep it DRY so don't have to repeat opening file and decode
func OpenAndDecode(filepath string) (image.Image, string, error) {
imgFile, err := os.Open(filepath)
if err != nil {
panic(err)
}
defer imgFile.Close()
img, format, err := image.Decode(imgFile)
if err != nil {
panic(err)
}
return img, format, nil
}
// Decode image.Image's pixel data into []*Pixel
func DecodePixelsFromImage(img image.Image, offsetX, offsetY int) []*Pixel {
pixels := []*Pixel{}
for y := 0; y <= img.Bounds().Max.Y; y++ {
for x := 0; x <= img.Bounds().Max.X; x++ {
p := &Pixel{
Point: image.Point{x + offsetX, y + offsetY},
Color: img.At(x, y),
}
pixels = append(pixels, p)
}
}
return pixels
}

TA貢獻1806條經(jīng)驗 獲得超8個贊
我正是為此目的建立了一個圖書館。
您可以按如下方式使用它;
import gim "github.com/ozankasikci/go-image-merge"
grids := []*gim.Grid{
{ImageFilePath: "test1.jpg"},
{ImageFilePath: "test2.png"},
}
// merge the images into a 2x1 grid
rgba, err := gim.New(grids, 2, 1).Merge()
// save the output to jpg or png
file, err := os.Create("file/path.jpg|png")
err = jpeg.Encode(file, rgba, &jpeg.Options{Quality: 80})
https://github.com/ozankasikci/go-image-merge
- 3 回答
- 0 關(guān)注
- 206 瀏覽
添加回答
舉報