从URL获取图片

- (void)viewDidLoad {

[super viewDidLoad];

NSString *urlString = @"http://xxxxxxx.png";

NSData *data = [NSData dataWithContentsOfURL:[NSURL  URLWithString:urlString]];

UIImage *image = [UIImage imageWithData:data]; // 取得图片

// 本地沙盒目录

NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

// 得到本地沙盒中名为"MyImage"的路径,"MyImage"是保存的图片名

NSString *imageFilePath = [path stringByAppendingPathComponent:@"MyImage"];

// 将取得的图片写入本地的沙盒中,其中0.5表示压缩比例,1表示不压缩,数值越小压缩比例越大

BOOL success = [UIImageJPEGRepresentation(image, 0.5) writeToFile:imageFilePath  atomically:YES];

if (success){

NSLog(@"写入本地成功");

}

UIImageView *imagView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 20, 100, 100)];

UIImage *img = [UIImage imageWithContentsOfFile:imageFilePath];

imagView.image = img;

[self.view addSubview:imagView];

}

你可能感兴趣的:(从URL获取图片)