在项目开发中,有时候图库选择或拍照上传图片时,会出现图片旋转 90° 的问题,暂发现大于 2M 的图会出现这个问题,下面是解决方法,在上传图片之前进行图片的方向调整即可。
//修正图片旋转问题
- (UIImage *)fixImageOrientation:(UIImage *)image {
//image 的 imageOrientation 属性记录有图片的方向信息
if (image.imageOrientation == UIImageOrientationUp)
return image;
CGAffineTransform transform = CGAffineTransformIdentity;
switch (image.imageOrientation) {
case UIImageOrientationDown:
case UIImageOrientationDownMirrored:
transform = CGAffineTransformTranslate(transform, image.size.width, image.size.height);
transform = CGAffineTransformRotate(transform, M_PI);
break;
case UIImageOrientationLeft:
case UIImageOrientationLeftMirrored:
transform = CGAffineTransformTranslate(transform, image.size.width, 0);
transform = CGAffineTransformRotate(transform, M_PI_2);
break;
case UIImageOrientationRight:
case UIImageOrientationRightMirrored:
transform = CGAffineTransformTranslate(transform, 0, image.size.height);
transform = CGAffineTransformRotate(transform, -M_PI_2);
break;
default:
break;
}
switch (image.imageOrientation) {
case UIImageOrientationUpMirrored:
case UIImageOrientationDownMirrored:
transform = CGAffineTransformTranslate(transform, image.size.width, 0);
transform = CGAffineTransformScale(transform, -1, 1);
break;
case UIImageOrientationLeftMirrored:
case UIImageOrientationRightMirrored:
transform = CGAffineTransformTranslate(transform, image.size.height, 0);
transform = CGAffineTransformScale(transform, -1, 1);
break;
default:
break;
}
CGContextRef contextRef = CGBitmapContextCreate(NULL, image.size.width, image.size.height, CGImageGetBitsPerComponent(image.CGImage), 0, CGImageGetColorSpace(image.CGImage), CGImageGetBitmapInfo(image.CGImage));
CGContextConcatCTM(contextRef, transform);
switch (image.imageOrientation) {
case UIImageOrientationLeft:
case UIImageOrientationLeftMirrored:
case UIImageOrientationRight:
case UIImageOrientationRightMirrored:
CGContextDrawImage(contextRef, CGRectMake(0,0,image.size.height,image.size.width), image.CGImage);
break;
default:
CGContextDrawImage(contextRef, CGRectMake(0,0,image.size.width,image.size.height), image.CGImage);
break;
}
CGImageRef imgRef = CGBitmapContextCreateImage(contextRef);
UIImage *newImage = [UIImage imageWithCGImage: imgRef];
CGContextRelease(contextRef);
CGImageRelease(imgRef);
return newImage;
}
网友评论