UIImage imageOrientation问题

来源:互联网 发布:什么是无线传感器网络 编辑:程序博客网 时间:2024/05/22 08:25

先提点学到的东西:
iOS 的相册中的照片,都是保留了原始的照片方向,大家看到的照片是以正确的方向显示出来的,这是由程序实现的
在做UIImage和CGImageRef转换的时候一定要注意,从相册里load进来的图,一定要看一下它的方向是否和你心目中的方向是一致的,因为CGImageRef 是不支持图片方向的。
UIImageView会自动处理图片方向问题
一段代码来描述CGImage处理方向的做法,来自http://stackoverflow.com/questions/1260249/resizing-uiimages-pulled-from-the-camera-also-rotates-the-uiimage;
看完这个真为自己的英文捉急!
-(UIImage*)imageByScalingToSize:(CGSize)targetSize
{
UIImage* sourceImage = self;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;

CGImageRef imageRef = [sourceImage CGImage];
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
CGColorSpaceRef colorSpaceInfo = CGImageGetColorSpace(imageRef);

if (bitmapInfo == kCGImageAlphaNone) {
bitmapInfo = kCGImageAlphaNoneSkipLast;
}

CGContextRef bitmap;

if (sourceImage.imageOrientation == UIImageOrientationUp || sourceImage.imageOrientation == UIImageOrientationDown) {
bitmap = CGBitmapContextCreate(NULL, targetWidth, targetHeight, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo);

} else {
bitmap = CGBitmapContextCreate(NULL, targetHeight, targetWidth, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo);

}

if (sourceImage.imageOrientation == UIImageOrientationLeft) {
CGContextRotateCTM (bitmap, radians(90));
CGContextTranslateCTM (bitmap, 0, -targetHeight);

} else if (sourceImage.imageOrientation == UIImageOrientationRight) {
CGContextRotateCTM (bitmap, radians(-90));
CGContextTranslateCTM (bitmap, -targetWidth, 0);

} else if (sourceImage.imageOrientation == UIImageOrientationUp) {
// NOTHING
} else if (sourceImage.imageOrientation == UIImageOrientationDown) {
CGContextTranslateCTM (bitmap, targetWidth, targetHeight);
CGContextRotateCTM (bitmap, radians(-180.));
}

CGContextDrawImage(bitmap, CGRectMake(0, 0, targetWidth, targetHeight), imageRef);
CGImageRef ref = CGBitmapContextCreateImage(bitmap);
UIImage* newImage = [UIImage imageWithCGImage:ref];

CGContextRelease(bitmap);
CGImageRelease(ref);

return newImage;
}
我遇到的一个奇葩的问题, 我屏幕旋转锁定的情况下调用:
1
- (void)captureStillImageAsynchronouslyFromConnection:(AVCaptureConnection *)connection - completionHandler:(void (^)(CMSampleBufferRef imageDataSampleBuffer, NSError *error))handler;
并且传入的AVCaptureConnection是这么赋值过的
1
if ([stillImageConnection isVideoOrientationSupported]) [stillImageConnection setVideoOrientation:_orientation];
然后我下了断点,并NSLog的orientation,发现他是标准的home键在下的AVCaptureVideoOrientationPortrait。
但是在block里面用imageDataSampleBuffer 生成的UIImage的时候 UIImage的方向居然是UIImageOrientationLeft
然后我的CGImage的坐标全乱掉了不说,UIImageView居然依旧显示正常……
欧道 K?

0 0
原创粉丝点击