Явор обнови решението на 14.11.2013 16:53 (преди над 4 години)
+package main
+
+import (
+ "fmt"
+ "strings"
+)
+
+type Pixel struct {
+ Red uint8
+ Green uint8
+ Blue uint8
+}
+
+func (pixel Pixel) String() string {
+ return fmt.Sprintf("Red: %d, Green: %d, Blue: %d", pixel.Red, pixel.Green, pixel.Blue)
+}
+
+func (pixel Pixel) Color() Pixel {
+ return pixel
+}
+
+type PixelData struct {
+ width uint64
+ height uint64
+ format string
+ hasAlpha bool
+ redIndex uint8
+ greenIndex uint8
+ blueIndex uint8
+ alphaIndex uint8
+ pixelLength uint8
+ data []byte
+}
+
+func (pixelData PixelData) InspectPixel(i uint64, j uint64) (result Pixel) {
+ //pixelBytes := pixelData.data
+ //fmt.Printf("%p %d %d\n", pixelData, i, j)
+ realIndex := (j*pixelData.width + i) * uint64(pixelData.pixelLength)
+ realData := pixelData.data[realIndex : realIndex+uint64(pixelData.pixelLength)]
+ redVal := realData[pixelData.redIndex]
+ greenVal := realData[pixelData.greenIndex]
+ blueVal := realData[pixelData.blueIndex]
+ if !pixelData.hasAlpha {
+ return Pixel{redVal, greenVal, blueVal}
+ }
+ alphaFactor := float64(realData[pixelData.alphaIndex]) / float64(255)
+ redVal = byte(alphaFactor * float64(redVal))
+ greenVal = byte(alphaFactor * float64(greenVal))
+ blueVal = byte(alphaFactor * float64(blueVal))
+ return Pixel{redVal, greenVal, blueVal}
+}
+
+type Header struct {
+ Format string
+ LineWidth uint64
+}
+
+func ParseImage(pixels []byte, header Header) (result PixelData) {
+ format := header.Format
+ pixelLength := uint8(len(format))
+ width := header.LineWidth
+ height := ((uint64)(len(pixels))) / width / uint64(pixelLength)
+ alphaIndex := strings.IndexRune(format, 'A')
+ hasAlpha := (alphaIndex != -1)
+ redIndex := strings.IndexRune(format, 'R')
+ if redIndex == -1 {
+ panic("Incorrect header format string: no 'red'")
+ }
+ greenIndex := strings.IndexRune(format, 'G')
+ if redIndex == -1 {
+ panic("Incorrect header format string: no 'green'")
+ }
+ blueIndex := strings.IndexRune(format, 'B')
+ if blueIndex == -1 {
+ panic("Incorrect header format string: no 'blue'")
+ }
+ fmt.Printf("%d %d\n", width, height)
+ result = PixelData{width, height, format, hasAlpha, uint8(redIndex),
+ uint8(greenIndex), uint8(blueIndex), uint8(alphaIndex), pixelLength, pixels}
+ return
+}
+
+/*func main() {
+ data := []byte{0, 12, 244, 13, 26, 52, 31, 33, 41}
+ header := Header{"RGB", 3}
+ pixelData := ParseImage(data, header)
+ fmt.Println(pixelData)
+ realPixel := pixelData.InspectPixel(0, 2)
+ fmt.Println(realPixel)
+}*/