iPhone - CGImageCreateWithImageInRect rotating some camera roll pictures

前端 未结 1 490
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-29 13:56

I am working on a pixelate application for iPhone. Because the pictures taken with the iPhone 4 camera are too big and therefore the application is working really slow when

相关标签:
1条回答
  • 2020-12-29 14:18

    It is because the imageOrientation isn't taken into account.

    There is a similar question (Resizing UIimages pulled from the Camera also ROTATES the UIimage?) and I've modified the code a bit to work with cropping image.

    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;
    }
    
    0 讨论(0)
提交回复
热议问题