Domanda

Ho un UIImage (Cocoa Touch). Da ciò, sono felice di ricevere un CGImage o qualsiasi altra cosa tu voglia che sia disponibile. Vorrei scrivere questa funzione:

- (int)getRGBAFromImage:(UIImage *)image atX:(int)xx andY:(int)yy {
  // [...]
  // What do I want to read about to help
  // me fill in this bit, here?
  // [...]

  int result = (red << 24) | (green << 16) | (blue << 8) | alpha;
  return result;
}

Grazie!

È stato utile?

Soluzione

Cordiali saluti, ho combinato la risposta di Keremk con il mio schema originale, ho ripulito gli errori di battitura, l'ho generalizzata per restituire una gamma di colori e ho fatto compilare il tutto. Ecco il risultato:

+ (NSArray*)getRGBAsFromImage:(UIImage*)image atX:(int)x andY:(int)y count:(int)count
{
    NSMutableArray *result = [NSMutableArray arrayWithCapacity:count];

    // First get the image into your data buffer
    CGImageRef imageRef = [image CGImage];
    NSUInteger width = CGImageGetWidth(imageRef);
    NSUInteger height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = bytesPerPixel * width;
    NSUInteger bitsPerComponent = 8;
    CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                    bitsPerComponent, bytesPerRow, colorSpace,
                    kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);

    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
    CGContextRelease(context);

    // Now your rawData contains the image data in the RGBA8888 pixel format.
    NSUInteger byteIndex = (bytesPerRow * y) + x * bytesPerPixel;
    for (int i = 0 ; i < count ; ++i)
    {
        CGFloat alpha = ((CGFloat) rawData[byteIndex + 3] ) / 255.0f;
        CGFloat red   = ((CGFloat) rawData[byteIndex]     ) / alpha;
        CGFloat green = ((CGFloat) rawData[byteIndex + 1] ) / alpha;
        CGFloat blue  = ((CGFloat) rawData[byteIndex + 2] ) / alpha;
        byteIndex += bytesPerPixel;

        UIColor *acolor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
        [result addObject:acolor];
    }

  free(rawData);

  return result;
}

Altri suggerimenti

Un modo per farlo è quello di disegnare l'immagine in un contesto bitmap supportato da un determinato buffer per un determinato spazio colore (in questo caso è RGB): (nota che questo copierà i dati dell'immagine in quel buffer, quindi vuoi memorizzarlo nella cache invece di fare questa operazione ogni volta che devi ottenere i valori dei pixel)

Vedi sotto come esempio:

// First get the image into your data buffer
CGImageRef image = [myUIImage CGImage];
NSUInteger width = CGImageGetWidth(image);
NSUInteger height = CGImageGetHeight(image);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);

CGContextDrawImage(context, CGRectMake(0, 0, width, height));
CGContextRelease(context);

// Now your rawData contains the image data in the RGBA8888 pixel format.
int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
red = rawData[byteIndex];
green = rawData[byteIndex + 1];
blue = rawData[byteIndex + 2];
alpha = rawData[byteIndex + 3];

Il Domande e risposte tecniche; Un QA1509 mostra il seguente approccio semplice:

CFDataRef CopyImagePixels(CGImageRef inImage)
{
    return CGDataProviderCopyData(CGImageGetDataProvider(inImage));
}

Usa CFDataGetBytePtr per arrivare ai byte effettivi (e vari metodi CGImageGet * per capire come interpretarli).

Impossibile credere che non ci sia non una sola risposta corretta qui. Non è necessario allocare i puntatori e i valori non moltiplicati devono ancora essere normalizzati. Per andare al sodo, ecco la versione corretta di Swift 4. Per UIImage basta usare .cgImage .

extension CGImage {
    func colors(at: [CGPoint]) -> [UIColor]? {
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bytesPerPixel = 4
        let bytesPerRow = bytesPerPixel * width
        let bitsPerComponent = 8
        let bitmapInfo: UInt32 = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue

        guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo),
            let ptr = context.data?.assumingMemoryBound(to: UInt8.self) else {
            return nil
        }

        context.draw(self, in: CGRect(x: 0, y: 0, width: width, height: height))

        return at.map { p in
            let i = bytesPerRow * Int(p.y) + bytesPerPixel * Int(p.x)

            let a = CGFloat(ptr[i + 3]) / 255.0
            let r = (CGFloat(ptr[i]) / a) / 255.0
            let g = (CGFloat(ptr[i + 1]) / a) / 255.0
            let b = (CGFloat(ptr[i + 2]) / a) / 255.0

            return UIColor(red: r, green: g, blue: b, alpha: a)
        }
    }
}

Ecco un SO thread in cui viene visualizzato @Matt solo il pixel desiderato in un contesto 1x1 spostando l'immagine in modo che il pixel desiderato si allinei con un pixel nel contesto.

NSString * path = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"jpg"];
UIImage * img = [[UIImage alloc]initWithContentsOfFile:path];
CGImageRef image = [img CGImage];
CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(image));
const unsigned char * buffer =  CFDataGetBytePtr(data);

UIImage è un wrapper i byte sono CGImage o CIImage

Secondo il Riferimento Apple su UIImage l'oggetto è immutabile e non si ha accesso ai byte di supporto. Sebbene sia vero che puoi accedere ai dati CGImage se hai popolato UIImage con un CGImage (esplicitamente o implicitamente), restituirà NULL se UIImage è supportato da un CIImage e viceversa.

  

Gli oggetti immagine non forniscono accesso diretto all'immagine sottostante   dati. Tuttavia, è possibile recuperare i dati di immagine in altri formati per   utilizzare nella tua app. In particolare, è possibile utilizzare cgImage e ciImage   proprietà per recuperare versioni dell'immagine compatibili   Core Graphics e Core Image, rispettivamente. Puoi anche usare il   UIImagePNGRepresentation ( :) e UIImageJPEGRepresentation (: _ :)   funzioni per generare un oggetto NSData contenente i dati dell'immagine   in formato PNG o JPEG.

Trucchi comuni per aggirare questo problema

Come indicato, le opzioni sono

  • UIImagePNGRepresentation o JPEG
  • Determina se l'immagine ha dati di supporto CGImage o CIImage e portali lì

Nessuno di questi è un trucco particolarmente utile se si desidera un output che non sia ARGB, PNG o JPEG e che i dati non siano già supportati da CIImage.

La mia raccomandazione, prova CIImage

Durante lo sviluppo del progetto potrebbe essere più sensato evitare completamente UIImage e scegliere qualcos'altro. UIImage, come wrapper di immagini Obj-C, è spesso supportato da CGImage al punto in cui lo diamo per scontato. CIImage tende ad essere un formato wrapper migliore in quanto è possibile utilizzare un CIContext per ottenere il formato desiderato senza bisogno di sapere come è stato creato. Nel tuo caso, ottenere la bitmap sarebbe una questione di chiamata

- render: toBitmap: rowBytes: bounds: formato: colorSpace:

Come bonus aggiuntivo puoi iniziare a fare delle belle manipolazioni all'immagine concatenando filtri sull'immagine. Questo risolve molti dei problemi in cui l'immagine è capovolta o deve essere ruotata / ridimensionata ecc.

Basandoci sulla risposta di Olie e Algal, ecco una risposta aggiornata per Swift 3

public func getRGBAs(fromImage image: UIImage, x: Int, y: Int, count: Int) -> [UIColor] {

var result = [UIColor]()

// First get the image into your data buffer
guard let cgImage = image.cgImage else {
    print("CGContext creation failed")
    return []
}

let width = cgImage.width
let height = cgImage.height
let colorSpace = CGColorSpaceCreateDeviceRGB()
let rawdata = calloc(height*width*4, MemoryLayout<CUnsignedChar>.size)
let bytesPerPixel = 4
let bytesPerRow = bytesPerPixel * width
let bitsPerComponent = 8
let bitmapInfo: UInt32 = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue

guard let context = CGContext(data: rawdata, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else {
    print("CGContext creation failed")
    return result
}

context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))

// Now your rawData contains the image data in the RGBA8888 pixel format.
var byteIndex = bytesPerRow * y + bytesPerPixel * x

for _ in 0..<count {
    let alpha = CGFloat(rawdata!.load(fromByteOffset: byteIndex + 3, as: UInt8.self)) / 255.0
    let red = CGFloat(rawdata!.load(fromByteOffset: byteIndex, as: UInt8.self)) / alpha
    let green = CGFloat(rawdata!.load(fromByteOffset: byteIndex + 1, as: UInt8.self)) / alpha
    let blue = CGFloat(rawdata!.load(fromByteOffset: byteIndex + 2, as: UInt8.self)) / alpha
    byteIndex += bytesPerPixel

    let aColor = UIColor(red: red, green: green, blue: blue, alpha: alpha)
    result.append(aColor)
}

free(rawdata)

return result
}

Basato su risposte diverse ma principalmente su questo , funziona per quello che mi serve:

UIImage *image1 = ...; // The image from where you want a pixel data
int pixelX = ...; // The X coordinate of the pixel you want to retrieve
int pixelY = ...; // The Y coordinate of the pixel you want to retrieve

uint32_t pixel1; // Where the pixel data is to be stored
CGContextRef context1 = CGBitmapContextCreate(&pixel1, 1, 1, 8, 4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst);
CGContextDrawImage(context1, CGRectMake(-pixelX, -pixelY, CGImageGetWidth(image1.CGImage), CGImageGetHeight(image1.CGImage)), image1.CGImage);
CGContextRelease(context1);

Come risultato di queste righe, avrai un pixel in formato AARRGGBB con alfa sempre impostato su FF nell'intero senza segno a 4 byte pixel1 .

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top