2016-08-02 6 views
3

ich eine Methode in this post eingeführt verwenden, für Swift geändert:Kann nicht Bytes für ein nicht-quadratisches Bild bekommen

func getRaster() -> [UIColor] { 
    let result = NSMutableArray() 

    let img = self.CGImage 
    let width = CGImageGetWidth(img) 
    let height = CGImageGetHeight(img) 
    let colorSpace = CGColorSpaceCreateDeviceRGB() 

    var rawData = [UInt8](count: width * height * 4, repeatedValue: 0) 
    let bytesPerPixel = 4 
    let bytesPerRow = bytesPerPixel * width 
    let bytesPerComponent = 8 

    let bitmapInfo = CGImageAlphaInfo.PremultipliedLast.rawValue | CGBitmapInfo.ByteOrder32Big.rawValue 
    let context = CGBitmapContextCreate(&rawData, width, height, bytesPerComponent, bytesPerRow, colorSpace, bitmapInfo) 

    CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), img); 
    for x in 0..<width { 
     for y in 0..<height { 
      let byteIndex = (bytesPerRow * x) + y * bytesPerPixel 

      let red = CGFloat(rawData[byteIndex] )/255.0 
      let green = CGFloat(rawData[byteIndex + 1])/255.0 
      let blue = CGFloat(rawData[byteIndex + 2])/255.0 
      let alpha = CGFloat(rawData[byteIndex + 3])/255.0 

      let color = UIColor(red: red, green: green, blue: blue, alpha: alpha) 
      result.addObject(color) 
     } 
    } 

    return (result as NSArray) as! [UIColor] 
} 

Aber das Problem ist, dass es immer nur erfolgreich, wenn das Bild quadratisch ist (dh 32x32 Sprite), wenn ich versuche, ein "Raster" eines Bildes, die Dimensionen sind nicht gleich, bekomme ich einen fatalen Fehler "Index außerhalb des Bereichs" für red auf x = 16 und y = 0 (für Bild der Größe h: 16, w: 32). Was könnte eine Lösung für dieses Problem sein?

Vielen Dank im Voraus!

+1

Nur um zu klären, ich habe die Interpretation für Swift-Version [hier] (http://stackoverflow.com/questions/38163523/uiimage-to-uicolor-array-of-pixel-colors). Es ist jetzt auch dort behoben. – EBDOKUM

+0

Dies wird viel Aufwand bei der Array-Neuzuweisung verursachen. Die Leistung würde sich erheblich verbessern, wenn Sie das Array vorab zuweisen. In der Tat, das hat wirklich keinen Grund, 'NSMutableArray' statt einer nativen Swift' Array' – Alexander

+0

@AMomchilov wieder zu verwenden, habe ich eine Implementierung, eingeführt in der [post] (http://stackoverflow.com/questions/38163523/uiimage-to-uicolor-Array-von-Pixel-Farben). Der, den ich praktisch benutze, ist ein bisschen anders und ja, ich stimme zu, dafür gibt es absolut keinen Grund. – EBDOKUM

Antwort

1

Es war recht einfach zu lösen, tatsächlich, hier ist das Problem Teil:

for x in 0..<width { 
    for y in 0..<height { 
     let byteIndex = (bytesPerRow * x) + y * bytesPerPixel 

Und hier ist, wie es sein soll ist:

for y in 0..<height { 
     for x in 0..<width { 
      let byteIndex = (bytesPerRow * y) + x * bytesPerPixel 

Ich glaube nicht, das keine weitere Erklärung bedarf.

Verwandte Themen