Александър обнови решението на 04.11.2013 14:04 (преди над 4 години)
+package main
+
+import "strconv"
+
+type Header struct {
+ Format string
+ LineWidth int
+}
+
+type Image struct {
+ pixelArray [][]Pixel
+ Width int
+ Height int
+}
+
+type Pixel struct {
+ color ColorComponents
+}
+
+type ColorComponents struct {
+ Red byte
+ Green byte
+ Blue byte
+}
+
+func (color ColorComponents) String() string {
+ return "Red: " + strconv.Itoa(int(color.Red)) + ", Green: " + strconv.Itoa(int(color.Green)) + ", Blue: " + strconv.Itoa(int(color.Blue))
+}
+
+func (pixel Pixel) Color() ColorComponents {
+ return pixel.color
+}
+
+func ParseImage(data []byte, header Header) Image {
+
+ componentCount := len(header.Format)
+
+ var image Image
+ image.Width = header.LineWidth
+ image.Height = len(data) / componentCount / image.Width
+ image.pixelArray = make([][]Pixel, image.Height)
+ for i := range image.pixelArray {
+ image.pixelArray[i] = make([]Pixel, image.Width)
+ }
+
+ var red int
+ var green int
+ var blue int
+ var alpha int
+ var xPos int
+ var yPos int
+
+ for i := range data {
+ colorCode := header.Format[i%componentCount]
+
+ switch {
+ case colorCode == 'R':
+ red = int(data[i])
+ case colorCode == 'G':
+ green = int(data[i])
+ case colorCode == 'B':
+ blue = int(data[i])
+ default:
+ alpha = int(data[i])
+ }
+
+ if i%componentCount == componentCount-1 { //this is the last component of the current pixel, so we have to save it
+ position := (i - componentCount + 1) / componentCount
+ xPos = position / image.Width
+ yPos = position - xPos*image.Width
+
+ if componentCount == 4 { //we have an alpha channel
+ red = red * alpha / 255
+ green = green * alpha / 255
+ blue = blue * alpha / 255
+ }
+
+ image.pixelArray[xPos][yPos].color.Red = byte(red)
+ image.pixelArray[xPos][yPos].color.Green = byte(green)
+ image.pixelArray[xPos][yPos].color.Blue = byte(blue)
+ }
+ }
+
+ return image
+}
+
+func (image Image) InspectPixel(x uint, y uint) Pixel {
+ return image.pixelArray[y][x]
+}