изображение, нажатое с iPhone в портретном режиме, поворачивается на 90 градусов - PullRequest
6 голосов
/ 12 мая 2011

Я загружаю изображение, нажатое с iphone, как в альбомном, так и в портретном режиме. Изображение в ландшафтном режиме загружается нормально, но проблема в том, что изображение загружено в портретном режиме. Они поворачиваются на 90 градусов.

Также отлично работают другие изображения в портретном режиме (не нажаты с iPhone).

Есть идеи, почему так происходит?

Ответы [ 3 ]

5 голосов
/ 12 мая 2011

В вашем делегате:

   - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

После того, как вы получили UIImage из словаря "info" для ключа "UIImagePickerControllerOriginalImage", вы можете увидеть ориентацию изображения по свойству imageOrientation.Если это не так, как вы хотите, просто поверните изображение перед загрузкой.

imageOrientation
The orientation of the receiver’s image. (read-only)

@property(nonatomic, readonly) UIImageOrientation imageOrientation
Discussion
Image orientation affects the way the image data is displayed when drawn. By default, images are displayed in the “up” orientation. If the image has associated metadata (such as EXIF information), however, this property contains the orientation indicated by that metadata. For a list of possible values for this property, see “UIImageOrientation.”

Availability
Available in iOS 2.0 and later.
Declared In
UIImage.h 

Ссылка на класс UIImage

Ссылка на класс UIImagePickerController

Справочник по протоколу UIImagePickerControllerDelegate

Второй параметр:

Позволяет пользователю редактировать ваше изображение и получать изображение для "UIImagePickerControllerEditedImage";

Установите для UIImagePickerController " allowEditing " свойство Yes.

В вашем делегате просто получите из словаря "info" UIImage для "UIImagePickerControllerEditedImage"ключ.

Удачи.

4 голосов
/ 17 марта 2012

Я довольно много боролся с этой проблемой, я работал над проектом, в котором мне нужно фактически повернуть изображение, как при переупорядочении пикселей, чтобы я мог загрузить его.

Сначалавсе, что вам нужно сделать, это определить ориентацию, затем удалить эти надоедливые метаданные, а затем повернуть изображение.

Итак, поместите это внутри функции didFinishPickingMediaWithInfo:

    UIImage * img = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

    if ([info objectForKey:@"UIImagePickerControllerMediaMetadata"]) {
    //Rotate based on orientation
    switch ([[[info objectForKey:@"UIImagePickerControllerMediaMetadata"] objectForKey:@"Orientation"] intValue]) {
        case 3:
            //Rotate image to the left twice.
            img = [UIImage imageWithCGImage:[img CGImage]];  //Strip off that pesky meta data!
            img = [rotateImage rotateImage:[rotateImage rotateImage:img withRotationType:rotateLeft] withRotationType:rotateLeft];
            break;

        case 6:
            img = [UIImage imageWithCGImage:[img CGImage]];
            img = [rotateImage rotateImage:img withRotationType:rotateRight];
            break;

        case 8:
            img = [UIImage imageWithCGImage:[img CGImage]];
            img = [rotateImage rotateImage:img withRotationType:rotateLeft];
            break;

        default:
            break;
    }
}

Ивот функция изменения размера:

+(UIImage*)rotateImage:(UIImage*)image withRotationType:(rotationType)rotation{
    CGImageRef imageRef = [image CGImage];
    CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef);
    CGColorSpaceRef colorSpaceInfo = CGColorSpaceCreateDeviceRGB();

    if (alphaInfo == kCGImageAlphaNone)
        alphaInfo = kCGImageAlphaNoneSkipLast;

        CGContextRef bitmap;

    bitmap = CGBitmapContextCreate(NULL, image.size.height, image.size.width, CGImageGetBitsPerComponent(imageRef), 4 * image.size.height/*CGImageGetBytesPerRow(imageRef)*/, colorSpaceInfo, alphaInfo);
    CGColorSpaceRelease(colorSpaceInfo);

    if (rotation == rotateLeft) {
        CGContextTranslateCTM (bitmap, image.size.height, 0);
        CGContextRotateCTM (bitmap, radians(90));
    }
    else{
        CGContextTranslateCTM (bitmap, 0, image.size.width);
        CGContextRotateCTM (bitmap, radians(-90));
    }

    CGContextDrawImage(bitmap, CGRectMake(0, 0, image.size.width, image.size.height), imageRef);
    CGImageRef ref = CGBitmapContextCreateImage(bitmap);
    UIImage *result = [UIImage imageWithCGImage:ref];
    CGImageRelease(ref);
    CGContextRelease(bitmap);
    return result;
}

Переменная img теперь содержит правильно повернутое изображение.

0 голосов
/ 07 ноября 2016

Хорошо, более чистая версия будет:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *img = [info valueForKey:UIImagePickerControllerOriginalImage];
    img = [UIImage imageWithCGImage:[img CGImage]];

    UIImageOrientation requiredOrientation = UIImageOrientationUp;
    switch ([[[info objectForKey:@"UIImagePickerControllerMediaMetadata"] objectForKey:@"Orientation"] intValue])
    {
        case 3:
            requiredOrientation = UIImageOrientationDown;
             break;
        case 6:
            requiredOrientation = UIImageOrientationRight;
            break;
        case 8:
            requiredOrientation = UIImageOrientationLeft;
            break;
        default:
            break;
    }

    UIImage *portraitImage = [[UIImage alloc] initWithCGImage:img.CGImage scale:1.0 orientation:requiredOrientation];

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...