【问题标题】:Converting CGImageRef image to image and that UIimage to NSData将 CGImageRef 图像转换为图像,并将 UIimage 转换为 NSData
【发布时间】:2012-04-19 12:34:02
【问题描述】:

我正在通过以下代码截取我上次查看的屏幕截图

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

当我在控制台中显示图像时,我得到的 O/P 如下: UIImage: 0x929c760
问题就在这里,当将该 UIImage 转换为 NSData 时,我得到了 null。

我尝试过的事情是

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

【问题讨论】:

  • 我正在将 CGContext 转换为 UIImage。现在 UIImage 将被转换为 NSData
  • 你没有用任何图像填充你的图形上下文 - 所以它是空的 stackoverflow.com/questions/2200736/…
  • 是的,我刚刚看到并且真的为我工作

标签: iphone ios4 ios5 xcode4.2


【解决方案1】:

大家好,@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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 2015-10-11
    • 2017-03-30
    • 2011-09-22
    • 2013-11-29
    • 1970-01-01
    相关资源
    最近更新 更多