2012-04-05 4 views
5

를 반환 여러 개의 이미지로 이미지를 분할하는 기능을 만들었지 만이있는 UIImage의의 CGImage을 취할 때의 CGImage NULL을 반환있는 UIImage의의 CGImage이 NULL

NSArray* splitImage(UIImage* image,NSUInteger pieces) { 

NSLog(@"width: %f, %zu",image.size.width,CGImageGetWidth(image.CGImage)); 
NSLog(@"%@",image.CGImage); 
returns NULL 
NSMutableArray* tempArray = [[NSMutableArray alloc]initWithCapacity:pieces]; 

CGFloat piecesSize = image.size.height/pieces; 

for (NSUInteger i = 0; i < pieces; i++) { 

    // take in account retina displays 
    CGRect subFrame = CGRectMake(0,i * piecesSize * image.scale ,image.size.width * image.scale,piecesSize * image.scale); 

    CGImageRef newImage = CGImageCreateWithImageInRect(image.CGImage,subFrame); 

    UIImage* finalImage =[UIImage imageWithCGImage:newImage]; 

    CGImageRelease(newImage); 

    [tempArray addObject:finalImage]; 

} 

NSArray* finalArray = [NSArray arrayWithArray:tempArray]; 

[tempArray release]; 

return finalArray; 



} 
+0

체크 tempArray는, 그것은 C 구조체 목적은 아니다 널 (null) 여부를 마지막 – Hector

+1

의 CGImage에, 그래서 당신은 %의 @와 NSLog를 사용하지 않아야합니다. – lnafziger

+0

문제는 IOSurface로 UIImage를 만들었다는 것입니다 : D – Otium

답변

4

의 CGImage 속성은 같은 IOSurface 또는 CIImage로 전무를 반환합니다. 이 특별한 경우에이 문제를 해결하기 위해 c 함수를 사용하여 IOSurface에서 CGImage를 생성 한 다음이를 UIImage로 변환 할 수 있습니다.

UICreateCGImageFromIOSurface(IOSurfaceRef surface); 
2

당신은 조각을 만들 지금 무슨 짓을 0.f 너비가 인 경우 두 개의 for을 사용하여 조각에 width & height을 정의해야합니다. 코드 샘플은 다음과 같습니다 (아직 테스트하지는 않았지만 제대로 작동 함).

for (int height = 0; height < image.size.height; height += piecesSize) { 
    for (int width = 0; width < image.size.width; width += piecesSize) { 
    CGRect subFrame = CGRectMake(width, height, piecesSize, piecesSize); 

    CGImageRef newImage = CGImageCreateWithImageInRect(image.CGImage, subFrame); 
    UIImage * finalImage = [UIImage imageWithCGImage:newImage]; 
    CGImageRelease(newImage); 

    [tempArray addObject:finalImage]; 
    } 
} 
+1

+1 나는 이것을 수행하는 (테스트 한) 코드가 있으며 제안과 일치합니다. Mine은 subimageInRect : (CGRect) rect라는 UIImage의 범주 메서드로 패키지되어 있습니다. 나는 그것이 더 예쁘다고 생각합니다. – danh

1

이미지를 자르려고하는 경우가 있습니다. 이 같은 솔루션이이 당신을 도울 수있을 수 있습니다 시도 발견 : -있는 UIImage 다른 이미지에서 만들어진 경우

NSData *imageData = UIImageJPEGRepresentation(yourImage, 0.9); 
newImage = [UIImage imageWithData:imageData]; 
2

나는 CGImage에서 UIImage을 만들었습니다.

CIImage *ciImage = image.CIImage; 
CIContext *context = [CIContext contextWithOptions:nil]; 
CGImageRef ref = [context createCGImage:ciImage fromRect:ciImage.extent]; 
UIImage *newImage = [UIImage imageWithCGImage:ref]; 

그리고 지금 newImage.CGImage하지 nil