NSData和UIImage之间的转换

来源:互联网 发布:h5麻将源码 编辑:程序博客网 时间:2024/05/17 23:33

源自:http://stackoverflow.com/questions/2240765/nsdata-to-uiimage

 

Try this code. This worked for me.

create path to save the image data.

NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                                                       
NSUserDomainMask,
                                                       YES
);
NSString *path = [[pathArr objectAtIndex:0]
                  stringByAppendingPathComponent
:@"img.data" ];

convert the image to NSData object

NSData* data = UIImageJPEGRepresentation(myImage, 1.0);
[data writeToFile:path atomically:YES];

retrieve the saved data

 NSData *retrievedData = [NSData dataWithContentsOfFile:path];

Create an imageview

UIImageView *imgv = [[UIImageView alloc] 
                      initWithFrame
:CGRectMake(100, 100, 200, 200)];

load the imageview with the retrieved data

imgv.image = [UIImage imageWithData:retrievedData];
[self.view addSubview:imgv];
[imgv release];