Q: How can I create an Image object from a UIImage without writing it to disk?
A:
You can create an Image object using an NSData buffer via he class method CreateImageWithData. Below is some sample code showing how to do so. Note that PDF images do not support alpha directly (you would need to construct a soft mask), so you will need to strip out the alpha channel, as shown below.
SDFDoc* doc = [[m_pdfViewCtrl GetDoc] GetSDFDoc];
NSData* data = [self getNSDataFromUIImage:myUIImage];
Obj* o = [[Obj alloc] init];
Image* trnImage = [Image CreateWithData:doc image_data:data image_data_size:data.length width:image.size.width height:image.size.heightbpc:8 color_space:[ColorSpace CreateDeviceRGB] encoder_hints:o];
where getNSDataFromUIImage is:
-(NSData*)getNSDataFromUIImage:(UIImage*)image
{
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char rawData = (unsigned char) malloc(height * width * 4 * sizeof(unsigned char));
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
unsigned char noAlpha = (unsigned char) malloc(height * width * 3* sizeof(unsigned char));
for(int pix = 0; pix < height * width * 4; pix += bytesPerPixel)
{
memcpy((noAlpha+pix/bytesPerPixel*3), (rawData+pix), 3);
}
NSData* data = [[NSData alloc] initWithBytesNoCopy:noAlpha length:heightwidth3*sizeof(unsigned char) freeWhenDone:YES];
free(rawData);
return data;
}