2011-12-13 12 views
7

Soy nuevo en iOS y he estado golpeando la cabeza contra la pared durante la última semana buscando en línea tutoriales como: Dealing with Exif Images, Resizing images, y muchos más preguntas al azar aquí en StackOverflow. De estos, calculé que >=iOS 4.0, todas las imágenes tomadas desde la cámara contienen información de rotación basada en EXIF.iOS: Recortar una imagen fija tomada de una cámara UIImagePickerController con superposición

lo que no funciona: Después de probar diferentes técnicas de imagen de cultivo, todo termino con que se recorte de la imagen en algunas esquinas al azar, y también, la imagen resultante parece estar enfocado en :(Cuando uso una imagen de png de Internet (que no contiene datos EXIF), el recorte está funcionando. Me refiero a esquinas aleatorias: la imagen termina recortada en la esquina superior derecha/superior izquierda y aumentada.

Lo que estoy tratando de lograr:
Estoy tratando de recortar una imagen 100 px desde arriba y 100 px desde abajo. Esencialmente, estoy usando dos tiras de superposición: 1 en la parte superior y 1 en la parte inferior con CGRect(0.0, 0.0, SCREEN_WIDTH, 100.0) [a 100.0 px franja alta en la parte superior] y otra CGRect(0.0, SCREEN_HEIGHT - 100, SCREEN_WIDTH, 100.0) [otra 100 px franja alta en la parte inferior]. Necesito obtener la imagen entre estas dos tiras: Supongo que la altura de la imagen es: SCREEN_HEIGHT - 200.0.

Viendo UIImagePickerController para la cámara con superposición:

 

    //SCREEN_HEIGHT = 480 and SCREEN_WIDTH = 320 
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; 

    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] == NO) 
    { 
     NSLog(@"Camera not available"); 
     return; 
    } 

    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; 
    imagePicker.delegate = self; 
    imagePicker.allowsEditing = NO; 


    // Hide the controls 
    imagePicker.showsCameraControls = NO; 
    imagePicker.navigationBarHidden = YES; 

    // Make camera view full screen 
    imagePicker.wantsFullScreenLayout = YES; 
    //imagePicker.cameraViewTransform = CGAffineTransformScale(imagePicker.cameraViewTransform, CAMERA_TRANSFORM_X, CAMERA_TRANSFORM_Y); 


    //Overlay 
    //OverlayView is a plain UIView with the CGRects mentioned in the question. 
    OverlayView *overlay = [[OverlayView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)]; 
    [overlay initOverlay:self]; 
    imagePicker.cameraOverlayView = overlay; 
    [self presentModalViewController:imagePicker animated:YES]; 
 

Código para girar la imagen basada en EXIF ​​imageOrientation propiedad y recortarla

 

- (UIImage *) cropImage: (UIImage *) originalImage 
{ 

    CGRect cropRect = CGRectMake(0, 100.0, SCREEN_WIDTH, SCREEN_HEIGHT - 100); 

    CGRect transformedRect = [self TransformCGRectForUIImageOrientation:cropRect :originalImage.imageOrientation :originalImage.size]; 

    CGImageRef resultImageRef = CGImageCreateWithImageInRect(originalImage.CGImage, transformedRect); 

    UIImage *newImage = [[[UIImage alloc] initWithCGImage:resultImageRef scale:1.0 orientation:originalImage.imageOrientation] autorelease]; 

    return newImage; 
} 

- (CGRect) TransformCGRectForUIImageOrientation: (CGRect) source: (UIImageOrientation) orientation: (CGSize) imageSize { 

    switch (orientation) { 
     case UIImageOrientationLeft: { // EXIF #8 
      CGAffineTransform txTranslate = CGAffineTransformMakeTranslation(
                      imageSize.height, 0.0); 
      CGAffineTransform txCompound = CGAffineTransformRotate(txTranslate, 
                    M_PI_2); 
      return CGRectApplyAffineTransform(source, txCompound); 
     } 
     case UIImageOrientationDown: { // EXIF #3 
      CGAffineTransform txTranslate = CGAffineTransformMakeTranslation(
                      imageSize.width, imageSize.height); 
      CGAffineTransform txCompound = CGAffineTransformRotate(txTranslate, 
                    M_PI); 
      return CGRectApplyAffineTransform(source, txCompound); 
     } 
     case UIImageOrientationRight: { // EXIF #6 
      CGAffineTransform txTranslate = CGAffineTransformMakeTranslation(
                      0.0, imageSize.width); 
      CGAffineTransform txCompound = CGAffineTransformRotate(txTranslate, 
                    M_PI + M_PI_2); 
      return CGRectApplyAffineTransform(source, txCompound); 
     } 
     case UIImageOrientationUp: // EXIF #1 - do nothing 
     default: // EXIF 2,4,5,7 - ignore 
      return source; 
    } 

 

El método cropImage parece funcionar para las imágenes descargadas de internet (que no contiene ninguna información de orientación). Me estoy quedando sin opciones. ¿Podría alguien ayudarme?

¡Gracias por leer!

+0

Sagar - hizo el método de abajo no causó su aplicación al colapso? – Dejell

+0

@Odelya ¿A qué método inferior se refiere? –

+0

La respuesta de Matt. Tengo el problema exacto y no tuve éxito durante un mes para recortar la imagen correctamente – Dejell

Respuesta

17

Cuando sea posible, es más fácil para saltar imágenes de dibujo con el núcleo gráfico:

- (UIImage *)cropImage:(UIImage *)oldImage { 
    CGSize imageSize = oldImage.size 
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(imageSize.width, 
                 imageSize.height - 200), 
              NO, 
              0.); 
    [oldImage drawAtPoint:CGPointMake(0, -100) 
       blendMode:kCGBlendModeCopy 
        alpha:1.]; 
    UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    return croppedImage; 
} 
+0

+1 Gracias, Matt. Intentando entender el código: la línea # 2 "selecciona" la imagen con la parte inferior 200 px recortada y luego coloca las nuevas imágenes 100 px hacia arriba de la imagen original, con lo que se recortan los 100 px superiores, y los 100 px inferiores ¿no? ¡Funcionó para mí! ¡¡Muchas gracias por tus esfuerzos!! Aunque la imagen recortada no es exactamente similar a la que se ve con la superposición de la cámara, probablemente tenga que modificar los nichos. un poco. Por cierto, este código no es seguro para subprocesos, ¿verdad? Y supongo que la lib de CG proporciona una manera segura de hacer subprocesos, así que sería genial usarla de manera segura. –

+1

Es seguro para subprocesos en iOS 4.0 y posterior, [QA 1637] (http://developer.apple.com/library/ios/#qa/qa1637/_index.html). – Mats

+0

+1, ¡Aceptado! Impresionante, esto funciona entonces - ¡maravillosamente! ¡GRACIAS UNA TONELADA! ¡Muy apreciado! –

Cuestiones relacionadas