golang read many images into one simegle image code example
Example: golang read many images into one simegle image
type Pixel struct {
Point image.Point
Color color.Color
}
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
}
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
}
func main() {
img1, _, err := OpenAndDecode("makey.png")
if err != nil {
panic(err)
}
img2, _, err := OpenAndDecode("sample.jpg")
if err != nil {
panic(err)
}
pixels1 := DecodePixelsFromImage(img1, 0, 0)
pixels2 := DecodePixelsFromImage(img2, 0, img1.Bounds().Max.Y)
pixelSum := append(pixels1, pixels2...)
newRect := image.Rectangle{
Min: img1.Bounds().Min,
Max: image.Point{
X: img2.Bounds().Max.X,
Y: img2.Bounds().Max.Y + img1.Bounds().Max.Y,
},
}
finImage := image.NewRGBA(newRect)
for _, px := range pixelSum {
finImage.Set(
px.Point.X,
px.Point.Y,
px.Color,
)
}
draw.Draw(finImage, finImage.Bounds(), finImage, image.Point{0, 0}, draw.Src)
out, err := os.Create("./output.png")
if err != nil {
panic(err)
os.Exit(1)
}
err = png.Encode(out, finImage)
if err != nil {
panic(err)
os.Exit(1)
}
}