2016-06-15 6 views
2

NSDataに変換したいCGImageRefがあるファイルに保存されていません。今、私はイメージをいくつかの一時的な場所に保存して、これをNSDataに取得することでこれを行います。イメージを保存せずにこれを行うにはどうすればよいですか?CGImageRefをNSDataに変換する

CGImageRef img = [[self system_Application] getScreenShot]; 
NSString *tempDirectory = NSTemporaryDirectory(); 
CFURLRef url = (CFURLRef)[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/abc.jpg",tempDirectory]]; 

CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, NULL); 
CGImageDestinationAddImage(destination, img, nil); 
if(!CGImageDestinationFinalize(destination)) 
    NSLog(@"Failed to write Image"); 

NSData *mydata = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/abc.jpg",tempDirectory]]; 
+2

あなたはそこにいくつかの情報を見つけて://stackoverflow.com/questions/19527902/converting-nsdata-to-cgimage-and-then-ba ck-to-nsdata-makes-the-file-too-big – Larme

+0

この回答は私が現在使っているのと同じ考え方を使っています。しかし、ディスクに書き込んだり読んだりすると、私はそれを変更したい。だから何かを提案してください – CodingIsComplex

答えて

4

私は次のようにこれを行うことができたします。http:

CFMutableDataRef newImageData = CFDataCreateMutable(NULL, 0); 
CGImageDestinationRef destination = CGImageDestinationCreateWithData(newImageData, kUTTypePNG, 1, NULL); 
CGImageDestinationAddImage(destination, img, nil); 
if(!CGImageDestinationFinalize(destination)) 
    NSLog(@"Failed to write Image"); 
NSData *newImage = (NSData *)newImageData; 
4

のiOS:

NSData *data = UIImageJPEGRepresentation([[UIImage alloc] initWithCGImage:img], 1) 

のMacOS:

NSImage *image = [[NSImage alloc] initWithCGImage:img size:NSSizeFromCGSize(CGSizeMake(100, 100))]; 
NSBitmapImageRep *imgRep = (NSBitmapImageRep *)[[image representations] objectAtIndex: 0]; 
NSData *data = [imgRep representationUsingType: NSPNGFileType properties: @{}]; 
+0

質問はココアのタグが付けられて、UIImageはココアタッチでのみ利用可能です。 – jrturton

+0

はい、あなたが正しいです、私は私の答えを更新しました – arturdev

関連する問題