iYahoo
iYahoo

Reputation: 184

Converting CGImageRef image to image and that UIimage to NSData

I am taking the screenshot of my last viewed Screen, by the following code

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

When i displayed the the image in the console i got the O/P like: UIImage: 0x929c760
The Problem lies here for me, When converting that UIImage to NSData i am getting null.

The things i have tried are

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

Upvotes: 0

Views: 6292

Answers (1)

iYahoo
iYahoo

Reputation: 184

Hi everyone i have got the solution to my Question as given by the link by @NP Compete //getting screenshot i haven't used any UIImageview so my code goes as following

-(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;
}

// Saved into Documents Directory

    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);

Upvotes: 2

Related Questions