IPhone - CGImageCreateWithImageInRect, rotating images of some cameras

I am working on a pixel app for iPhone. Since the pictures taken with the iPhone 4 camera are too large, and therefore the application is very slow when updating the pixel image, I try to create image tiles first and just refresh the tiles, not the hole image.

When creating tiles, it works for camera cameras made in landscape mode (2592 x 1936 pxl) and with low-resolution images, but not with images made in portrait mode (1936 x 2592 pxl).

The code for cutting tiles from the original image is as follows:

for (i = 0; i < NrOfTilesPerHeight; i++) { for (j = 0; j < NrOfTilesPerWidth; j++) { CGRect imageRect = CGRectMake(j*TILE_WIDTH, i*TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT); CGImageRef image = CGImageCreateWithImageInRect(aux.CGImage, imageRect); UIImage *img = [UIImage imageWithCGImage:image]; UIImageView *imgView = [[UIImageView alloc] initWithImage:img]; } } 

The problem is that the image created using these plates rotates 90 degrees counterclockwise.

Thank you so much Andrey

+7
source share
1 answer

This is because imageOrientation is not taken into account.

There is a similar question ( Resizing UIimages extracted from the camera, also ROTATES UIimage? ), And I slightly changed the code for working with image cropping.

Here you are:

 static inline double radians (double degrees) {return degrees * M_PI/180;} +(UIImage*)cropImage:(UIImage*)originalImage toRect:(CGRect)rect{ CGImageRef imageRef = CGImageCreateWithImageInRect([originalImage CGImage], rect); CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); CGColorSpaceRef colorSpaceInfo = CGImageGetColorSpace(imageRef); CGContextRef bitmap = CGBitmapContextCreate(NULL, rect.size.width, rect.size.height, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo); if (originalImage.imageOrientation == UIImageOrientationLeft) { CGContextRotateCTM (bitmap, radians(90)); CGContextTranslateCTM (bitmap, 0, -rect.size.height); } else if (originalImage.imageOrientation == UIImageOrientationRight) { CGContextRotateCTM (bitmap, radians(-90)); CGContextTranslateCTM (bitmap, -rect.size.width, 0); } else if (originalImage.imageOrientation == UIImageOrientationUp) { // NOTHING } else if (originalImage.imageOrientation == UIImageOrientationDown) { CGContextTranslateCTM (bitmap, rect.size.width, rect.size.height); CGContextRotateCTM (bitmap, radians(-180.)); } CGContextDrawImage(bitmap, CGRectMake(0, 0, rect.size.width, rect.size.height), imageRef); CGImageRef ref = CGBitmapContextCreateImage(bitmap); UIImage *resultImage=[UIImage imageWithCGImage:ref]; CGImageRelease(imageRef); CGContextRelease(bitmap); CGImageRelease(ref); return resultImage; } 
+7
source

All Articles