Георги обнови решението на 05.11.2013 15:05 (преди над 4 години)
+package main
+
+import "fmt"
+
+type Header struct {
+ Format string
+ lineWidth int
+}
+
+type Image struct {
+ lineWidth int
+ pixels []Pixel
+}
+
+type Pixel struct {
+ color Color
+}
+
+type Color struct {
+ Red, Green, Blue byte
+}
+
+func (p *Pixel) String() string {
+ return fmt.Sprintln("Red:", p.color.Red, " Green:", p.color.Green, " Blue:", p.color.Blue)
+}
+
+func (pixel *Pixel) Color() Color {
+ return pixel.color
+}
+
+func ParseImage(data []byte, header Header) Image {
+ pixelsNumber := len(data) / len(header.Format)
+ pixels := make([]Pixel, pixelsNumber)
+ pixelComponents := len(header.Format)
+ var r, g, b, a byte
+ a = 255
+ for i := 0; i < pixelsNumber; i++ {
+ for j := 0; j < pixelComponents; j++ {
+ switch string(header.Format[j]) {
+ case "R":
+ r = data[i*pixelComponents+j]
+
+ case "G":
+ g = data[i*pixelComponents+j]
+
+ case "B":
+ b = data[i*pixelComponents+j]
+
+ case "A":
+ a = data[i*pixelComponents+j]
+ }
+ }
+ pixels[i].color = AlphaBlend(r, g, b, a)
+ }
+ image := Image{header.lineWidth, pixels}
+
+ return image
+}
+
+func AlphaBlend(r, g, b, a byte) Color {
+ var (
+ alpha float32 = float32(a) / 255
+ red float32 = (float32(r) / 255) * alpha
+ green float32 = (float32(g) / 255) * alpha
+ blue float32 = (float32(b) / 255) * alpha
+ )
+
+ color := Color{byte(red*255 + 0.5), byte(green*255 + 0.5), byte(blue*255 + 0.5)}
+
+ return color
+}
+
+func (img *Image) InspectPixel(x, y int) Pixel {
+ pixelIndex := y*img.lineWidth + x
+ return img.pixels[pixelIndex]
+}