将CGImageRef图像转换为图像,将UIimage转换为NSData

时间:2012-04-19 12:34:02

标签: iphone ios4 ios5 xcode4.2

我正在通过以下代码

获取我上次查看过的屏幕的屏幕截图
//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);

1 个答案:

答案 0 :(得分:2)

大家好,我已经通过@NP Compete的链接获得了我的问题的解决方案 //获取截图我没有使用任何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);
相关问题