Skip to content

Instantly share code, notes, and snippets.

@NickSablukov
Created August 1, 2022 05:33
Show Gist options
  • Save NickSablukov/42327b9460cfd26bc5cf990f63555190 to your computer and use it in GitHub Desktop.
Save NickSablukov/42327b9460cfd26bc5cf990f63555190 to your computer and use it in GitHub Desktop.
func (b *MosaicBuilder) Build() error {
b.logger.Println("Load parts paths ...")
partsPaths, err := b.getPartsPaths()
if err != nil {
return err
}
b.logger.Println("Load parts map ...")
partsMap, err := b.getPartsMap(partsPaths)
if err != nil {
return err
}
b.logger.Println("Open source image ...")
img, err := os.Open("img.jpg")
defer func(img *os.File) { _ = img.Close() }(img)
if err != nil {
return err
}
src, err := jpeg.Decode(img)
if err != nil {
return err
}
b.logger.Println("calculate ...")
imgSize := src.Bounds().Size()
if imgSize.X > 300 {
src = resize.Resize(300, 0, src, resize.Lanczos3)
}
if imgSize.Y > 300 {
src = resize.Resize(0, 300, src, resize.Lanczos3)
}
imgSize = src.Bounds().Size()
partSize := int(b.partSize)
resImg := image.NewRGBA(
image.Rectangle{
Min: image.Point{},
Max: image.Point{X: imgSize.X * partSize, Y: imgSize.Y * partSize},
},
)
for x := 0; x < imgSize.X; x++ {
for y := 0; y < imgSize.Y; y++ {
bcolor := src.At(x, y)
part := getClosestPart(&partsMap, bcolor)
for px := 0; px < partSize; px++ {
for py := 0; py < partSize; py++ {
partPixel := color.RGBAModel.Convert(part.At(px, py)).(color.RGBA)
resImg.Set(partSize*x+px, partSize*y+py, partPixel)
}
}
}
}
b.logger.Println("save res ...")
f, err := os.Create("res.png")
if err != nil {
return err
}
if err := png.Encode(f, resImg); err != nil {
return err
}
b.logger.Println("done!")
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment