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

前端 未结 7 1471
野趣味
野趣味 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:13

    For the more obtuse among us (read: future me) here's some working code based on Itay and Dave R's answers. It starts with a UIImage and ends with a modified UIImage:

        // load image
        UIImage *image      = [UIImage imageNamed:@"test.png"];
        CGImageRef imageRef = image.CGImage;
        NSData *data        = (NSData *)CGDataProviderCopyData(CGImageGetDataProvider(imageRef));
        char *pixels        = (char *)[data bytes];
    
        // this is where you manipulate the individual pixels
        // assumes a 4 byte pixel consisting of rgb and alpha
        // for PNGs without transparency use i+=3 and remove int a
        for(int i = 0; i < [data length]; i += 4)
        {
            int r = i;
            int g = i+1;
            int b = i+2;
            int a = i+3;
    
            pixels[r]   = 0; // eg. remove red
            pixels[g]   = pixels[g];
            pixels[b]   = pixels[b];
            pixels[a]   = pixels[a];
        }
    
        // create a new image from the modified pixel data
        size_t width                    = CGImageGetWidth(imageRef);
        size_t height                   = CGImageGetHeight(imageRef);
        size_t bitsPerComponent         = CGImageGetBitsPerComponent(imageRef);
        size_t bitsPerPixel             = CGImageGetBitsPerPixel(imageRef);
        size_t bytesPerRow              = CGImageGetBytesPerRow(imageRef);
    
        CGColorSpaceRef colorspace      = CGColorSpaceCreateDeviceRGB();
        CGBitmapInfo bitmapInfo         = CGImageGetBitmapInfo(imageRef);
        CGDataProviderRef provider      = CGDataProviderCreateWithData(NULL, pixels, [data length], NULL);
    
        CGImageRef newImageRef = CGImageCreate (
                                  width,
                                  height,
                                  bitsPerComponent,
                                  bitsPerPixel,
                                  bytesPerRow,
                                  colorspace,
                                  bitmapInfo,
                                  provider,
                                  NULL,
                                  false,
                                  kCGRenderingIntentDefault
                                  );
        // the modified image
        UIImage *newImage   = [UIImage imageWithCGImage:newImageRef];
    
        // cleanup
        free(pixels);
        CGImageRelease(imageRef);
        CGColorSpaceRelease(colorspace);
        CGDataProviderRelease(provider);
        CGImageRelease(newImageRef);
    

提交回复
热议问题