2012-07-03 1 views

답변

2

나는 이미지의 구형 영역에 적용 할 다른 항목의 코드를 수정했습니다.

typedef enum { 
    ALPHA = 0, 
    BLUE = 1, 
    GREEN = 2, 
    RED = 3 
} PIXELS; 

- (UIImage *)convertToGrayscale:(UIImage *) originalImage inRect: (CGRect) rect{ 
    CGSize size = [originalImage size]; 
    int width = size.width; 
    int height = size.height; 

    // the pixels will be painted to this array 
    uint32_t *pixels = (uint32_t *) malloc(width * height * sizeof(uint32_t)); 

    // clear the pixels so any transparency is preserved 
    memset(pixels, 0, width * height * sizeof(uint32_t)); 

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 

    // create a context with RGBA pixels 
    CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width * sizeof(uint32_t), colorSpace, 
               kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast); 

    // paint the bitmap to our context which will fill in the pixels array 
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), [originalImage CGImage]); 

    for(int y = 0; y < height; y++) { 
     for(int x = 0; x < width; x++) { 
      uint8_t *rgbaPixel = (uint8_t *) &pixels[y * width + x]; 

      if(x > rect.origin.x && y > rect.origin.y && x < rect.origin.x + rect.size.width && y < rect.origin.y + rect.size.height) { 

       // convert to grayscale using recommended method: http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale 

       uint32_t gray = 0.3 * rgbaPixel[RED] + 0.59 * rgbaPixel[GREEN] + 0.11 * rgbaPixel[BLUE]; 

       // set the pixels to gray in your rect 

       rgbaPixel[RED] = gray; 
       rgbaPixel[GREEN] = gray; 
       rgbaPixel[BLUE] = gray; 
      } 
     } 
    } 

    // create a new CGImageRef from our context with the modified pixels 
    CGImageRef image = CGBitmapContextCreateImage(context); 

    // we're done with the context, color space, and pixels 
    CGContextRelease(context); 
    CGColorSpaceRelease(colorSpace); 
    free(pixels); 

    // make a new UIImage to return 
    UIImage *resultUIImage = [UIImage imageWithCGImage:image]; 

    // we're done with image now too 
    CGImageRelease(image); 

    return resultUIImage; 
} 

당신은있는 UIImageView에서 테스트 할 수 있습니다

imageview.image = [self convertToGrayscale:imageview.image inRect:CGRectMake(50, 50, 100, 100)]; 
+0

감사 바젤 압델 같은 효과에 적합합니다, 나는 우리가 CMSampleBufferRef와 동일한 기능을 수행 할 수있는 것 같아요. 권리? –

+0

잘 모르겠지만 CMSampleBufferRef에 대한 다른 질문을 검색하면 그렇게 생각됩니다. – Basel

관련 문제