Note that there are some explanatory texts on larger screens.

plurals
  1. POGetting a Black and White UIImage (Not Grayscale)
    text
    copied!<p>I need to get a pure black and white UIImage from another UIImage (not grayscale). Anyone can help me?</p> <p>Thanks for reading.</p> <p><strong>EDITED:</strong></p> <p>Here is the proposed solution. Thanks to all. Almost I know that is not the better way to do it, it works fine.</p> <pre><code>// Gets an pure black and white image from an original image. - (UIImage *)pureBlackAndWhiteImage:(UIImage *)image { unsigned char *dataBitmap = [self bitmapFromImage:image]; for (int i = 0; i &lt; image.size.width * image.size.height * 4; i += 4) { if ((dataBitmap[i + 1] + dataBitmap[i + 2] + dataBitmap[i + 3]) &lt; (255 * 3 / 2)) { dataBitmap[i + 1] = 0; dataBitmap[i + 2] = 0; dataBitmap[i + 3] = 0; } else { dataBitmap[i + 1] = 255; dataBitmap[i + 2] = 255; dataBitmap[i + 3] = 255; } } image = [self imageWithBits:dataBitmap withSize:image.size]; return image; } </code></pre> <p><strong>EDITED 1:</strong></p> <p>In response to comments, Here are methods <code>bitmapFromImage</code> and <code>imageWithBits</code>.</p> <pre><code>// Retrieves the bits from the context once the image has been drawn. - (unsigned char *)bitmapFromImage:(UIImage *)image { // Creates a bitmap from the given image. CGContextRef contex = CreateARGBBitmapContext(image.size); if (contex == NULL) { return NULL; } CGRect rect = CGRectMake(0.0f, 0.0f, image.size.width, image.size.height); CGContextDrawImage(contex, rect, image.CGImage); unsigned char *data = CGBitmapContextGetData(contex); CGContextRelease(contex); return data; } // Fills an image with bits. - (UIImage *)imageWithBits:(unsigned char *)bits withSize:(CGSize)size { // Creates a color space CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); if (colorSpace == NULL) { fprintf(stderr, "Error allocating color space\n"); free(bits); return nil; } CGContextRef context = CGBitmapContextCreate (bits, size.width, size.height, 8, size.width * 4, colorSpace, kCGImageAlphaPremultipliedFirst); if (context == NULL) { fprintf (stderr, "Error. Context not created\n"); free (bits); CGColorSpaceRelease(colorSpace ); return nil; } CGColorSpaceRelease(colorSpace ); CGImageRef ref = CGBitmapContextCreateImage(context); free(CGBitmapContextGetData(context)); CGContextRelease(context); UIImage *img = [UIImage imageWithCGImage:ref]; CFRelease(ref); return img; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload