简体   繁体   中英

how to change rgb value of an image in iOS?

I have a UIImage and I want to decrease the rgb value of each point , how can I do that? or how can I change one color to another color in an image? [Xcode8 , swift3]

One of the ways is to use image as a template and to set color which you want.

extension UIImageView {
func changeImageColor( color:UIColor) -> UIImage
{
    image = image!.withRenderingMode(.alwaysTemplate)
    tintColor = color
    return image!
}
}

  //Change color of logo 
   logoImage.image =  logoImage.changeImageColor(color: .red)

This answer only applies if you want to change individual pixels..

First use UIImage.cgImage to get a CGImage . Next, create a bitmap context using CGBitmapContextCreate with the CGColorSpaceCreateDeviceRGB colour space and whatever blend modes you want.

Then call CGContextDrawImage to draw the image to the context which is backed by a pixel array provided by you. Cleanup, and you now have an array of pixels.

- (uint8_t*)getPixels:(UIImage *)image {
    CGColorSpaceRef cs= CGColorSpaceCreateDeviceRGB();
    uint8_t *pixels= malloc(image.size.width * image.size.height * 4);
    CGContextRef ctx= CGBitmapContextCreate(rawData, image.size.width, image.size.height, 8, image.size.width * 4, cs, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(cs);

    CGContextDrawImage(ctx, CGRectMake(0, 0, image.size.width, image.size.height));
    CGContextRelease(ctx);
    return pixels;
}

Modify the pixels however you want.. Then recreate the image from the pixels..

- (UIImage *)imageFromPixels:(uint8_t *)pixels width:(NSUInteger)width height:(NSUInteger)height {
    CGDataProviderRef provider = CGDataProviderCreateWithData(nil, pixels, width * height * 4, nil);

    CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
    CGImageRef cgImageRef = CGImageCreate(width, height, 8, 32, width * 4, cs, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast, provider, nil, NO, kCGRenderingIntentDefault);

    pixels = malloc(width * height * 4);
    CGContextRef ctx = CGBitmapContextCreate(pixels, width, height, 8, width * 4, cs, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast);

    CGContextDrawImage(ctx, (CGRect) { .origin.x = 0, .origin.y = 0, .size.width = width, .size.height = height }, cgImage); 
    CGImageRef cgImage = CGBitmapContextCreateImage(ctx);
    UIImage *image = [UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);
    CGContextRelease(ctx);
    CGColorSpaceRelease(cs);
    CGImageRelease(cgImageRef);
    CGDataProviderRelease(provider);
    free(pixels);
    return image;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM