SORU
15 Ocak 2009, PERŞEMBE


Nasıl Uİİmage (Cocoa Touch) veya CGİmage (Çekirdek Grafikleri) bir piksel verilerini almak için?

Bir Uİİmage (Cocoa Touch) var. Bu, bir CGİmage veya mevcut istediğin başka bir şey almak için mutluyum. Bu fonksiyon yazmak istiyorum:

- (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;
}

Teşekkürler!

CEVAP
11 AĞUSTOS 2009, Salı


BİLGİNİZE, benim orijinal anahat ile Keremk cevabı, temizlenmiş yazım hataları birleştirdim, renk bir dizi dönmek için genelleştirilmiş ve derlemek için her şey var. İşte sonuç:

  (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 red   = (rawData[byteIndex]     * 1.0) / 255.0;
        CGFloat green = (rawData[byteIndex   1] * 1.0) / 255.0;
        CGFloat blue  = (rawData[byteIndex   2] * 1.0) / 255.0;
        CGFloat alpha = (rawData[byteIndex   3] * 1.0) / 255.0;
        byteIndex  = bytesPerPixel;

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

  free(rawData);

  return result;
}

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Alan Fullmer

    Alan Fullmer

    3 EYLÜL 2010
  • Jeb Corliss

    Jeb Corliss

    17 Kasım 2006
  • NightShader1

    NightShader1

    25 Temmuz 2006