Изображение в масштабе iOS, снятое с камеры

Я пытаюсь написать код, в котором пользователь может сделать снимок со своей камеры, и затем он будет отображаться внутри указанного UIImageView, а также загружаться на сервер для последующего пользователя. В качестве устройства использую iPad. Однако, когда пользователь делает снимок, он поворачивается на 90 градусов. Кроме того, он неправильно масштабирован. Соотношение сторон отличается от того, что было сделано на фотографии. Это код, который я использую для масштабирования и изменения размера: http://pastebin.com/HxNkb7Be

При загрузке файла на мой сервер я получаю данные изображения следующим образом:

NSData *imageData = UIImageJPEGRepresentation(scaleAndRotateImage(image), 0.90f);

Вот как я получаю UIImage с камеры:

// Get the asset representation
ALAssetRepresentation *rep = [asset defaultRepresentation];

// Get the right orientation
UIImageOrientation orientation = UIImageOrientationUp;
NSNumber *orientationValue = [[rep metadata] objectForKey:@"Orientation"];
if (orientationValue != nil) {
    orientation = [orientationValue intValue];
}

// Get the CG image reference and convert to UIImage
UIImage *image = [UIImage imageWithCGImage:[rep fullResolutionImage] scale:rep.scale orientation:orientation];

person Jon Erickson    schedule 31.10.2013    source источник


Ответы (1)


Возможно, это связано с используемым вами вспомогательным методом [rep fullResolutionImage]. Ниже приведен хороший метод, который вы можете использовать для достижения желаемого. (это также решит проблему масштабирования)

 - (UIImage *)image:(UIImage *)image scaledCopyOfSize:(CGSize)newSize {

 UIDeviceOrientation deviceOrientation = [[UIDevice currentDevice] orientation];
 UIImageOrientation imageOrientation = UIImageOrientationLeft;

 switch (deviceOrientation)
 {
 case UIDeviceOrientationPortrait:
 imageOrientation = UIImageOrientationRight;
 NSLog(@"UIImageOrientationRight");
 break;
 case UIDeviceOrientationPortraitUpsideDown:
 imageOrientation = UIImageOrientationLeft;
 NSLog(@"UIImageOrientationLeft");
 break;
 case UIDeviceOrientationLandscapeLeft:
 imageOrientation = UIImageOrientationUp;
 NSLog(@"UIImageOrientationUp");
 break;
 case UIDeviceOrientationLandscapeRight:
 imageOrientation = UIImageOrientationDown;
 NSLog(@"UIImageOrientationDown");
 break;
 default:
 NSLog(@"Default");
 imageOrientation = UIImageOrientationRight ;
 break;
 }

 CGImageRef imgRef = image.CGImage;

 CGFloat width = CGImageGetWidth(imgRef);
 CGFloat height = CGImageGetHeight(imgRef);

 CGAffineTransform transform = CGAffineTransformIdentity;
 CGRect bounds = CGRectMake(0, 0, width, height);
 if (width > newSize.width || height > newSize.height) {
 CGFloat ratio = width/height;
 if (ratio > 1) {
 bounds.size.width = newSize.width;
 bounds.size.height = bounds.size.width / ratio;
 }
 else {
 bounds.size.height = newSize.height;
 bounds.size.width = bounds.size.height * ratio;
 }
 }

 CGFloat scaleRatio = bounds.size.width / width;
 CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
 CGFloat boundHeight;
 UIImageOrientation orient = imageOrientation;
 switch(orient) {

 case UIImageOrientationUp: //EXIF = 1
 transform = CGAffineTransformIdentity;
 break;

 case UIImageOrientationUpMirrored: //EXIF = 2
 transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
 transform = CGAffineTransformScale(transform, -1.0, 1.0);
 break;

 case UIImageOrientationDown: //EXIF = 3
 transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
 transform = CGAffineTransformRotate(transform, M_PI);
 break;

 case UIImageOrientationDownMirrored: //EXIF = 4
 transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
 transform = CGAffineTransformScale(transform, 1.0, -1.0);
 break;

 case UIImageOrientationLeftMirrored: //EXIF = 5
 boundHeight = bounds.size.height;
 bounds.size.height = bounds.size.width;
 bounds.size.width = boundHeight;
 transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
 transform = CGAffineTransformScale(transform, -1.0, 1.0);
 transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
 break;

 case UIImageOrientationLeft: //EXIF = 6
 boundHeight = bounds.size.height;
 bounds.size.height = bounds.size.width;
 bounds.size.width = boundHeight;
 transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
 transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
 break;

 case UIImageOrientationRightMirrored: //EXIF = 7
 boundHeight = bounds.size.height;
 bounds.size.height = bounds.size.width;
 bounds.size.width = boundHeight;
 transform = CGAffineTransformMakeScale(-1.0, 1.0);
 transform = CGAffineTransformRotate(transform, M_PI / 2.0);
 break;

 case UIImageOrientationRight: //EXIF = 8
 boundHeight = bounds.size.height;
 bounds.size.height = bounds.size.width;
 bounds.size.width = boundHeight;
 transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
 transform = CGAffineTransformRotate(transform, M_PI / 2.0);
 break;

 default:
 [NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];

 }

 UIGraphicsBeginImageContext(bounds.size);

 CGContextRef context = UIGraphicsGetCurrentContext();

 if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
 CGContextScaleCTM(context, -scaleRatio, scaleRatio);
 CGContextTranslateCTM(context, -height, 0);
 }
 else {
 CGContextScaleCTM(context, scaleRatio, -scaleRatio);
 CGContextTranslateCTM(context, 0, -height);
 }

 CGContextConcatCTM(context, transform);

 CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
 UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();

 return imageCopy;
 }
person Thilina Hewagama    schedule 31.10.2013
comment
Прекрасно работает. Однако я закомментировал ту часть, которая препятствует масштабированию вверх изображения. Казалось лишним, так как ничто в сигнатуре метода не подразумевает, что он может только уменьшаться. И если все, что вы хотите сделать, это уменьшить, CGImageSourceCreateThumbnailAtIndex, возможно, будет более кратким решением. - person aroth; 06.01.2014