我使用以下代码保存和加载从库中拾取或使用相机拍摄的图像:

//saving an image
- (void)saveImage:(UIImage*)image:(NSString*)imageName {
    NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
    NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
    NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]]; //add our image to the path
    [fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)
    NSLog(@"image saved");
}

//loading an image
- (UIImage*)loadImage:(NSString*)imageName {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]];
    return [UIImage imageWithContentsOfFile:fullPath];
}

这是我如何设置拾取的图像以在我的UIImageView中显示:

imgView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

然而,当我选取图像并将其设置为显示在我的UIImageView中时,这是可以的,但当我加载该图像时,它通常是错误的方向.有什么 idea 吗?有没有人经历过,或者知道我如何解决这个问题?

谢谢

编辑:

所以看起来,如果你加载一张照片,它是一张倒挂在肖像上的照片,它加载在那个方向上,如果你在横向拍摄一张照片,它加载在那个方向上.有什么办法吗?无论加载的方向是什么,它们总是以UIImageOrientationUp返回.

推荐答案

我也遇到过类似的问题,下面是我如何解决的.

当我们保存图像时,我们需要将save its orientation information与图像一起保存...

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setInteger:[myImage imageOrientation] forKey:@"kImageOrientation"];
[imageOrientation release];

然后我们把需要read its orientation information and apply it的图像加载到图像中…

UIImage *tempImage = [[UIImage alloc] initWithContentsOfFile:fullPath];
UIImage *orientedImage= [[UIImage alloc] initWithCGImage: tempImage.CGImage scale:1.0 orientation:imageOrientation];
[tempImage release];

orientedImage是我们需要的.

谢谢

Objective-c相关问答推荐

iOS 7 表格视图无法自动调整内容插入

XCTAssertEqual 不适用于双精度值

Asihttprequest 61 错误

将 NSNumber 转换为 NSDecimalNumber

判断正在使用的应用程序版本

静态和动态单元格的 UITableView 混合?

如何在目标 C 中创建单例类

检测到与加载的库不匹配的 UUID

如果用户禁用了应用程序的推送,是否可以进行静默远程通知?

滚动后检测 UITableView 中的当前顶部单元格

如何将日期字符串解析为 iOS 中的 NSDate 对象?

如何在 Objective-C 中创建静态方法?

dyld:找不到符号:try 运行 iOS 应用程序时的 _NSURLAuthenticationMethodClientCertificate

了解 performSegueWithIdentifier

可变集合有文字语法吗?

我可以在 Objective-C switch 语句中声明变量吗?

cellForRowAtIndexPath 是如何工作的?

Xcode - 如何将 XIB 连接到 ViewController 类

iPhone UILabel 文字软阴影

如何为 iPhone 6/7 自定义边到边图像指定尺寸?