Created
August 1, 2022 05:33
-
-
Save NickSablukov/42327b9460cfd26bc5cf990f63555190 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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