Can I edit the pixels of the UIImage's property CGImage

前端 未结 7 1450
野趣味
野趣味 2020-11-28 05:04

UIImage has a read-only property CGImage. I have to read its pixels to a memory block and edit them and then make a new UIImage to replace the old one. I want to know if th

7条回答
  •  暖寄归人
    2020-11-28 05:12

    You cannot get at the original pixels. However, you can get a copy. One option is to do what Matt suggested, and convert it into a PNG/JPG - though remember, the image is now compressed, and you will be manipulating the compressed file and not the pixels directly.

    If you want to get at a copy of the raw pixels, you can do something like:

    UIImage* image = ...; // An image
    NSData* pixelData = (NSData*) CGDataProviderCopyData(CGImageGetDataProvider(image.CGImage));
    void* pixelBytes = [pixelData bytes];
    
    // Take away the red pixel, assuming 32-bit RGBA
    for(int i = 0; i < [pixelData length]; i += 4) {
        bytes[i] = 0; // red
        bytes[i+1] = bytes[i+1]; // green
        bytes[i+2] = bytes[i+2]; // blue
        bytes[i+3] = bytes[i+3]; // alpha
    }
    

    Now, if you wanted to make this into a new UIImage, you can do something like:

    NSData* newPixelData = [NSData dataWithBytes:pixelBytes length:[pixelData length]];
    UIImage* newImage = [UIImage imageWithData:newPixelData]; // Huzzah
    

提交回复
热议问题