今天测试项目的改变头像功能,上午一直在用模拟器测试,没有任何问题,然后刚刚使用了真机来测。发现一个问题:昨天拍的猫的照片,上传上去之后,方向不对!因此就有了本文
原因
因为模拟器是没有拍照功能的,然后使用ALAsset保存到本地的图片,方向默认是正确的。
但是真机,由于拍照的时候,会有方向的概念,所以,模拟器上传不会出现上述问题。
解决方法
直接上代码
#pragma mark - UIImagePickerController delegate- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {if (info[UIImagePickerControllerEditedImage]) {UIImage *img = (UIImage *)info[UIImagePickerControllerEditedImage];UIImageOrientation imageOrientation = img.imageOrientation;[self saveImage:img withDirection:imageOrientation];}else {UIImage *img = (UIImage *)info[UIImagePickerControllerOriginalImage];UIImageOrientation imageOrientation = img.imageOrientation;[self saveImage:img withDirection:imageOrientation];}[picker dismissViewControllerAnimated:true completion:nil];}- (void)saveImage:(UIImage *)image withDirection:(UIImageOrientation)direction {if(direction != UIImageOrientationUp){// 原始图片可以根据照相时的角度来显示,但UIImage无法判定,于是出现获取的图片会向左转90度的现象。// 以下为调整图片角度的部分UIGraphicsBeginImageContext(image.size);[image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];image = UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();// 调整图片角度完毕}//获取图片的长宽,然后截取其中居中部分的正方形CGImageRef imgRef = image.CGImage;CGFloat imgWidth = CGImageGetWidth(imgRef);CGFloat imgHeight = CGImageGetHeight(imgRef);CGImageRef clipImgRef;if (imgWidth > imgHeight) {clipImgRef = CGImageCreateWithImageInRect(imgRef, CGRectMake((imgWidth - imgHeight)/2, 0, imgHeight, imgHeight));}else if (imgHeight > imgWidth) {clipImgRef = CGImageCreateWithImageInRect(imgRef, CGRectMake(0,(imgHeight - imgWidth)/2, imgWidth, imgWidth));}UIImage *scaleImg = [UIImage imageWithCGImage:clipImgRef];NSData *data = UIImageJPEGRepresentation([self scaleFromImage:scaleImg size:CGSizeMake(150, 150)], 1);self.showImgView.image = [UIImage imageWithData:data];}
代码详见github