Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Image from unsigned char *

Tags:

ios

image

iphone

I am trying to create a new Image from raw data in unsigned char *. I have the bits per pixel from the data stored. I tried converting raw data into NSData, But result image was nil,

unsigned char *bitmap = myData;

NSUInteger myImageDataLength = strlen( (const char*)bitmap);

NSData *d = [NSData dataWithBytes:bitmap length:myImageDataLength];

imgView.image = [UIImage imageWithData:d];

Then I tried using context to create an image as follows:

CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
int width = mWidth;
int height = mHeight;
size_t bpp = mBpp;
size_t bpc = 8;
size_t bpr = (width * 4);
CGContextRef context = CGBitmapContextCreate(bitmap, width, height, 8, bpr, colorspace, kCGImageAlphaNone);
CGImageRef cgImage = nil;
if (context != nil) {
    cgImage = CGBitmapContextCreateImage (context);
    CGContextRelease(context);
}
CGColorSpaceRelease(colorspace);
UIImage *newImage = [UIImage imageWithCGImage:cgImage];

I am getting an error message like <Error>: CGBitmapContextCreate: unsupported parameter combination: 8 integer bits/component; 24 bits/pixel; 3-component color space; kCGImageAlphaNone; 64 bytes/row.

I tried solving it by setting many values but cant find any result. I googled on internet to find this solution but all others are creating an image from existing images so they get the values of bits per components and all that... How can I create image from this data???

Original Image:

enter image description here

Resulting image:

enter image description here

Resulting image should be warped. (Warped same as fatBooth and other application)

like image 631
DivineDesert Avatar asked Aug 29 '11 04:08

DivineDesert


1 Answers

The following code creates a UIImage instance from raw pixel data assuming you have:

  • pixelData: the raw pixel data
  • imageWidth, imageHeight: the image dimensions
  • scanWidth: the number of bytes per scanline
  • bytesPerPixel: the number of bytes used per pixel, usually 4

The resulting UIImage is assigned to the variable uiImage.

CGDataProviderRef provider = CGDataProviderCreateWithData(
    NULL, 
    pixelData, 
    imageHeight * scanWidth, 
    NULL);

CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;

CGImageRef imageRef = CGImageCreate(imageWidth,
    imageHeight,
    8,
    bytesPerPixel * 8,
    scanWidth,
    colorSpaceRef,
    bitmapInfo,
    provider,
    NULL,
    NO,
    renderingIntent);

UIImage *uiImage = [UIImage imageWithCGImage:imageRef];
CGDataProviderRelease(provider);
CGColorSpaceRelease(colorSpaceRef);
CGImageRelease(imageRef);
like image 194
Codo Avatar answered Sep 18 '22 19:09

Codo