转换CGImageRef图像图像和的UIImage到NSData的

问题描述:

我带着我最后一次查看的屏幕截图,通过下面的代码转换CGImageRef图像图像和的UIImage到NSData的

//Image Code 
UIImage *nextImage; 
CGImageRef imgRef = CGBitmapContextCreateImage(UIGraphicsGetCurrentContext()); 
nextImage = [UIImage imageWithCGImage:imgRef]; 
CGImageRelease(imgRef); 
CGContextRelease(UIGraphicsGetCurrentContext()); 

当我显示在控制台中的形象我得到的O/P像:UIImage:0x929c760
问题在于我这里,当将UIImage转换为NSData我变空。

我曾尝试事情是

//tried  
NSData *data = UIImagePNGRepresentation(nextImage); 
NSData *data2 = UIImageJPEGRepresentation(nextImage, 1.0); 
+0

我CONV将CGContext切割成UIImage。现在UIImage将被转换为NSData – iYahoo 2012-04-19 12:46:09

+1

您不是用任何图像填充图形上下文 - 因此它是空的http://stackoverflow.com/questions/2200736/how-to-take-a-screenshot-programmatically – 2012-04-19 14:14:37

+0

是啊我刚刚看到了,真的为我工作 – iYahoo 2012-04-20 05:03:10

大家好我已经得到了解决我的问题由@NP链接给出竞争 //获取截图我没有使用任何的UIImageView所以我代码放在如下

-(UIImage*)doImageOperation 
{ 
    UIImage *image = [[UIImage alloc]init]; 
    UIGraphicsBeginImageContext(self.bounds.size); 
    [self.layer renderInContext:UIGraphicsGetCurrentContext()]; 
    image = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    NSLog(@"image in cg %@",image); 
    [self saveImage:image]; 
    return image; 
} 

//保存到文档目录

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
      NSString *documentsDirectory = [paths objectAtIndex:0]; 
      path = [documentsDirectory stringByAppendingPathComponent: 
        [NSString stringWithString:@"test.png"]]; 
data = UIImagePNGRepresentation(image); 
     [data writeToFile:path atomically:YES]; 
NSData *data = UIImagePNGRepresentation(image1); 
     NSLog(@"data %@",data);