2011-11-09 3 views
4

CGImageCreateWithImageInRect를 사용하여 사진을자를 때가 있습니다. 내 응용 프로그램은 사용자가 316 x 316보기를 채울 때까지 이미지를 이동/확대 한 다음 상자 외부의 모든 영역을 자르고 UIImage로 이미지를 저장하려고합니다. x와 y 이미지 뷰 원점의 절대 값을 취하여 자르기 원점을 결정합니다. 이미지 뷰를 포함하는 뷰/상자의 0,0으로 다시 가져옵니다. 코드는 다음과 같습니다.CGImageCreateWithImageInRect가 올바르게 자르지 않음

CGRect croppedRect = CGRectMake(fabs(widthDistanceToOrigin), fabs(HeightDistanceToOrigin), 316, 316); 
    CGImageRef croppedImageRef = CGImageCreateWithImageInRect(image.CGImage, croppedRect); 
    UIImage *croppedImage = [UIImage imageWithCGImage: croppedImageRef scale: 1/(imageScale) orientation: image.imageOrientation]; 
    CGImageRelease(croppedImageRef); 

이것은 나를 미치게합니다. 나는 정확하게 크기를 맞춰야하지만, 문제는 x와 y 원점의 자르기 직사각형과 같아서, 찍어야 할 영역에서 조금 벗어났습니다 (때로는 이상한 결과를 얻습니다).

또한 휴대 전화 카메라로 찍은 이미지의 경우 올바른 크기가되도록 자르기 직사각형의 모든 부분에 2를 곱해야합니다. 엄청 이상해.

누구나이 문제를 해결하는 방법을 알고 있거나 다른 사람이 자르기에 더 좋은 방법이 있는지 궁금합니다 (내 사진에서 영역을 잘라야한다는 사실을 명심하십시오). 감사!

+0

솔루션에서 답을 제공하고 시스템에서 허용하는 경우 받아들입니다. –

답변

0

문제점을 발견했습니다. 이미지를 크기 조정하기 전에 작물 영역을 움켜 잡으려했습니다. 이제 "CGImageCreateWithImageInRect"를 수행하기 전에 이미지를 줄이는 방법을 찾아야합니다. CGImageCreateWithImageInRect 하지만 그들 중 누구도 완벽하게 잘립니다하려고 무엇 미스 위치의 문제를 해결하지 :

4

은 그들 모두가 똑같은 대답을 가지고이 주제에 대한 많은 게시물이, 을 활용한다.

단, 하나 개의 스레드 (깊이 깊이 내 매장은), CGImageCreateWithImageInRect (image.CGImage, croppedRect에가는 다른 사람이없는 것을 사소한 세부 ... How to crop a UIImageView to a new UIImage in 'aspect fit' mode?

'RECT'매개 변수가 있습니다) 은 (UIImageView가 아니라) UIImage를 나타낼 필요가 있습니다.

이것은 좌표계상의 미스 포지셔닝 문제를 해결해야합니다.

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo: (NSDictionary *)info 
{ 
     oImage = [info valueForKey:UIImagePickerControllerOriginalImage]; 
     NSLog(@"Original Image size width: %f x height: %f", oImage.size.width, oImage.size.height); 


     // crop image according to what the image picker view is displaying 
     CGRect rect = CGRectMake(0, 40, 960.0f, 960.0f); // note: 960 x 1280 is what natively comes from capturing and image 
     nImage = [BGViewModifiers cropImage:oImage inRect:rect]; 

     // scale image down for display and creating kombie 
     CGSize size = CGSizeMake(320.0f, 320.0f); 
     nImage = [BGViewModifiers imageFromImage:nImage scaledToSize:size]; 

     NSLog(@"New Image size width: %f x height: %f", [nImage size].width, [nImage size].height); 
} 

//ref: http://stackoverflow.com/a/25293588/2298002 
+ (UIImage *)cropImage:(UIImage*)image inRect:(CGRect)rect 
{ 
    double (^rad)(double) = ^(double deg) { 
     return deg/180.0 * M_PI; 
    }; 

    CGAffineTransform rectTransform; 
    switch (image.imageOrientation) { 
     case UIImageOrientationLeft: 
      rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -image.size.height); 
      break; 
     case UIImageOrientationRight: 
      rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -image.size.width, 0); 
      break; 
     case UIImageOrientationDown: 
      rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -image.size.width, -image.size.height); 
      break; 
     default: 
      rectTransform = CGAffineTransformIdentity; 
    }; 
    rectTransform = CGAffineTransformScale(rectTransform, image.scale, image.scale); 

    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectApplyAffineTransform(rect, rectTransform)); 
    UIImage *result = [UIImage imageWithCGImage:imageRef scale:image.scale orientation:image.imageOrientation]; 
    CGImageRelease(imageRef); 

    return result; 
} 

+ (UIImage*)imageFromImage:(UIImage*)image scaledToSize:(CGSize)newSize 
{ 
    UIGraphicsBeginImageContext(newSize); 
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)]; 
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    return newImage; 
} 
2

나는 내 자신의 경험에 근거하여 더 많은 정보/답변을 제공해 드리고 싶습니다.

UIImage (따라서 CGImageCreateWithImageInRect:) 관점에서 (0, 0)은 왼쪽 하단에 있습니다. 자르기 사각형을 결정할 때, 당신은 단순히 표준 세로 방향에 따라 광장을 계산할 수 있습니다 후 주조 오류를 수정 CGFloat를 사용하는 명확성을 위해 다시 여기에 게시 및 변경 (@ 온실의 대답의 방법을 사용합니다.

- (UIImage *)cropImage:(UIImage*)image toRect:(CGRect)rect { 
    CGFloat (^rad)(CGFloat) = ^CGFloat(CGFloat deg) { 
     return deg/180.0f * (CGFloat) M_PI; 
    }; 

    // determine the orientation of the image and apply a transformation to the crop rectangle to shift it to the correct position 
    CGAffineTransform rectTransform; 
    switch (image.imageOrientation) { 
     case UIImageOrientationLeft: 
      rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -image.size.height); 
      break; 
     case UIImageOrientationRight: 
      rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -image.size.width, 0); 
      break; 
     case UIImageOrientationDown: 
      rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -image.size.width, -image.size.height); 
      break; 
     default: 
      rectTransform = CGAffineTransformIdentity; 
    }; 

    // adjust the transformation scale based on the image scale 
    rectTransform = CGAffineTransformScale(rectTransform, image.scale, image.scale); 

    // apply the transformation to the rect to create a new, shifted rect 
    CGRect transformedCropSquare = CGRectApplyAffineTransform(rect, rectTransform); 
    // use the rect to crop the image 
    CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, transformedCropSquare); 
    // create a new UIImage and set the scale and orientation appropriately 
    UIImage *result = [UIImage imageWithCGImage:imageRef scale:image.scale orientation:image.imageOrientation]; 
    // memory cleanup 
    CGImageRelease(imageRef); 

    return result; 
} 

이 코드는 자르기 사각형을 정확한 상대 위치로 이동시킵니다.

+0

나를 위해 완벽하게 작동했습니다. –

관련 문제