前言:
不曾想到我会无意遇到这个 bug。也困扰了我一天半。
起因是老大上班的时候看美女教练发的图片,然后查看图片大图的时候,发现图片旋转了,本来头朝上的,点开后发现头朝左。
然后我就去看bug。
效果图:
代码地址:
代码地址:https://github.com/gityuency/ObjectiveCTools
示例代码类名 【ImageOrientationViewController】
上代码!
ImageOrientationViewController.m
#import "ImageOrientationViewController.h"
@interface ImageOrientationViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageViewOri;
@property (weak, nonatomic) IBOutlet UIImageView *imageViewNew;
@property (strong, nonnull) UIImage *image;
@end
@implementation ImageOrientationViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:@"忘了爱" ofType:@"jpg"];
self.image = [UIImage imageWithContentsOfFile:path];
self.imageViewOri.image = self.image;
NSLog(@"原始图片的旋转: %ld", (long)self.image.imageOrientation);
}
- (IBAction)actionToLeft90:(UIButton *)sender {
if (self.image.imageOrientation == UIImageOrientationUp) {
UIImage *rotatedImage = [UIImage imageWithCGImage:self.image.CGImage scale:1.0f orientation:UIImageOrientationLeft];
self.imageViewNew.image = rotatedImage;
NSLog(@"处理后的旋转: %ld", (long)rotatedImage.imageOrientation);
//保存图片的到相册
//UIImageWriteToSavedPhotosAlbum(rotatedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
if(error){
NSLog(@"保存图片失败");
} else {
NSLog(@"保存图片成功");
}
}
@end
我后来发现,项目中有处理图片旋转的类,就比如 :
"UIImage+YYAdditions.h"
"UIImage+BeeExtension.h"
这样的,里面都有个函数: - (UIImage *)fixOrientation;
但是,经过实践发现,调用这个函数之后,图片的 “imageOrientation” 属性值确实改变了(从 2 -> 0),但是图片仍旧没有旋转过来,也就是说,我被骗了。浪费了好长时间。项目里面前任程序猿还改了 SDWebimage的源码,都特么是些骚操作。老大明明知道是图片的问题,还让我拿这个 bug 玩了一天。最终解决却只需要三行代码。行吧。
关于图片旋转可以看这里:
如何旋转UIImage 90度?
结语
愿天堂没有bug