0

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]

芮星晨
  • 123
  • 1
  • 9

2 Answers2

0

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)
Ivan Skrobot
  • 311
  • 3
  • 7
0

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;
}
Brandon
  • 22,723
  • 11
  • 93
  • 186