保存 UIImage,以错误的方向加载它

发布于 2024-12-10 21:35:20 字数 1762 浏览 0 评论 0原文

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

//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 中显示,这很好,但是当我加载该图像时,它通常是错误的方向。有什么想法吗?有人经历过这个或者知道我该如何解决这个问题吗?

谢谢。

编辑:

看来,如果您加载一张以纵向倒置的照片拍摄的照片,它会以该方向加载,如果您以横向拍摄的照片左侧,它会以该方向加载。有什么想法可以解决这个问题吗?无论加载方向如何,它们总是以 UIImageOrientationUp 形式返回。

I am using the following code to save and load images that I pick from either the library or take using the camera:

//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];
}

This is how I set the picked image to be shown in my UIImageView:

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

However, when I pick and image and set it to be shown in my UIImageView it is fine, but when I load that image it often is the wrong orientation. Any ideas? Anyone experienced this or know how I could resolve this?

Thanks.

EDIT:

So it seems, if you load a photo which was taken a photo in portrait upside-down, it loads in that orientation, if you take a photo in landscape left it loads in that orientation. Any ideas how to get around this? Whatever orientation they load it they always return as UIImageOrientationUp.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

聆听风音 2024-12-17 21:35:21

也尝试保存图像方向,然后当您加载该图像时,检查方向是否正确,如果不正确,请使用 CGAffineTransform 或任何您想要的方式旋转图像。

Try to save the image orientation too, then when you load that image, check if that's the correct orientation, and if not, rotate the image with CGAffineTransform or whatever you want.

故事未完 2024-12-17 21:35:21

您可以使用图像 I/O 将 PNG 图像相对于原始图像的方向保存到文件(或 NSMutableData )。在下面的示例中,我将 PNG 图像保存到 path 处的文件中。

- (BOOL)savePngFile:(UIImage *)image toPath:(NSString *)path {
    NSData *data = UIImagePNGRepresentation(image);
    int exifOrientation = [UIImage cc_iOSOrientationToExifOrientation:image.imageOrientation];
    NSDictionary *metadata = @{(__bridge id)kCGImagePropertyOrientation:@(exifOrientation)};
    NSURL *url = [NSURL fileURLWithPath:path];
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    if (!source) {
        return NO;
    }
    CFStringRef UTI = CGImageSourceGetType(source);
    CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef)url, UTI, 1, NULL);
    if (!destination) {
        CFRelease(source);
        return NO;
    }
    CGImageDestinationAddImageFromSource(destination, source, 0, (__bridge CFDictionaryRef)metadata);
    BOOL success = CGImageDestinationFinalize(destination);
    CFRelease(destination);
    CFRelease(source);
    return success;
}

cc_iOSOrientationToExifOrientation:UIImage类别的方法。

+ (int)cc_iOSOrientationToExifOrientation:(UIImageOrientation)iOSOrientation {
    int exifOrientation = -1;
    switch (iOSOrientation) {
        case UIImageOrientationUp:
            exifOrientation = 1;
            break;

        case UIImageOrientationDown:
            exifOrientation = 3;
            break;

        case UIImageOrientationLeft:
            exifOrientation = 8;
            break;

        case UIImageOrientationRight:
            exifOrientation = 6;
            break;

        case UIImageOrientationUpMirrored:
            exifOrientation = 2;
            break;

        case UIImageOrientationDownMirrored:
            exifOrientation = 4;
            break;

        case UIImageOrientationLeftMirrored:
            exifOrientation = 5;
            break;

        case UIImageOrientationRightMirrored:
            exifOrientation = 7;
            break;

        default:
            exifOrientation = -1;
    }
    return exifOrientation;
}

您也可以使用 CGImageDestinationCreateWithData 将图像保存到 NSMutableData,并在 CGImageDestinationCreateWithURL< 中传递 NSMutableData 而不是 NSURL /代码>。

You can use Image I/O to save PNG image to file(or NSMutableData) with respect to the orientation of the original image. In the example below I save the PNG image to a file at path.

- (BOOL)savePngFile:(UIImage *)image toPath:(NSString *)path {
    NSData *data = UIImagePNGRepresentation(image);
    int exifOrientation = [UIImage cc_iOSOrientationToExifOrientation:image.imageOrientation];
    NSDictionary *metadata = @{(__bridge id)kCGImagePropertyOrientation:@(exifOrientation)};
    NSURL *url = [NSURL fileURLWithPath:path];
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    if (!source) {
        return NO;
    }
    CFStringRef UTI = CGImageSourceGetType(source);
    CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef)url, UTI, 1, NULL);
    if (!destination) {
        CFRelease(source);
        return NO;
    }
    CGImageDestinationAddImageFromSource(destination, source, 0, (__bridge CFDictionaryRef)metadata);
    BOOL success = CGImageDestinationFinalize(destination);
    CFRelease(destination);
    CFRelease(source);
    return success;
}

cc_iOSOrientationToExifOrientation: is a method of UIImage category.

+ (int)cc_iOSOrientationToExifOrientation:(UIImageOrientation)iOSOrientation {
    int exifOrientation = -1;
    switch (iOSOrientation) {
        case UIImageOrientationUp:
            exifOrientation = 1;
            break;

        case UIImageOrientationDown:
            exifOrientation = 3;
            break;

        case UIImageOrientationLeft:
            exifOrientation = 8;
            break;

        case UIImageOrientationRight:
            exifOrientation = 6;
            break;

        case UIImageOrientationUpMirrored:
            exifOrientation = 2;
            break;

        case UIImageOrientationDownMirrored:
            exifOrientation = 4;
            break;

        case UIImageOrientationLeftMirrored:
            exifOrientation = 5;
            break;

        case UIImageOrientationRightMirrored:
            exifOrientation = 7;
            break;

        default:
            exifOrientation = -1;
    }
    return exifOrientation;
}

You can alternatively save the image to NSMutableData using CGImageDestinationCreateWithData and pass NSMutableData instead of NSURL in CGImageDestinationCreateWithURL.

明明#如月 2024-12-17 21:35:20

根本原因是 PNG 格式没有图像方向信息,但 JPEG 格式有。因此,解决此问题的最简单方法是使用 UIImageJPEGRepresentation() 将文件保存为 JPEG 格式

The root cause is PNG format doesn't have image orientation information, but JPEG format does. So the easiest way to solve this problem is saving your file in JPEG format using UIImageJPEGRepresentation()

空袭的梦i 2024-12-17 21:35:20

我也遇到过类似的问题,这就是我的解决方法。

当我们保存图像时,我们需要将其方向信息与图像一起保存...

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

而我们加载图像时,我们需要读取其方向信息并将其应用于图像...

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

orientationImage 就是我们所需要的。

谢谢,

I have faced similar problem and here is how I solved it.

While we save image we need to save its orientation information along with the image ...

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

And we load image we need to read its orientation information and apply it to the image…

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

orientedImage is what we need.

Thanks,

空城缀染半城烟沙 2024-12-17 21:35:20

检查您正在加载的图像的 EXIF 信息,应该有一个方向标签。使用该值将图像旋转到正确的方向。

这个网站应该可以帮助您入门。

http://www.impulseadventure.com/photo/exif-orientation.html

(您用来查看照片的应用程序必须内置此功能,这就是为什么您在打开照片时看到正确的方向)

Check the EXIF information for the image that you're loading, there should be a tag for orientation. Use the value to rotate your image to proper orientation.

This website should get you started.

http://www.impulseadventure.com/photo/exif-orientation.html

(The application you used to view the photo must have this built in, that's why you see correct orientation when opening the photo)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文