项目中需要将UIImage图片保存为JPG图片,iOS中提供了这样的实现方法
UIImage *getImage = [UIImage imageWithContentsOfFile:file];
NSData *data;
if (UIImagePNGRepresentation(getImage) == nil){
data = UIImageJPEGRepresentation(getImage, 1);
} else {
data = UIImagePNGRepresentation(getImage);
}
其中UIImageJPEGRepresentation函数需要两个参数:图片的引用和压缩系数
而且默认情况下UIImageJPEGRepresentation返回的数据大小也要比UIImagePNGRepresentation小很多
如果要返回第一个图片地址,可以把图片保存到本地后,在输出图片地址:
//照片获取本地路径转换
-(NSString *)getImagePath:(UIImage *)Image {
NSString * filePath = nil;
NSData * data = nil;
if (UIImagePNGRepresentation(Image) == nil) {
data = UIImageJPEGRepresentation(Image, 0.5);
} else {
data = UIImagePNGRepresentation(Image);
}
//图片保存的路径
//这里将图片放在沙盒的documents文件夹中
NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//文件管理器
NSFileManager *fileManager = [NSFileManager defaultManager];
//把刚刚图片转换的data对象拷贝至沙盒中
[fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
NSString * ImagePath = [[NSString alloc]initWithFormat:@"/theFirstImage.png"];
[fileManager createFileAtPath:[DocumentsPath stringByAppendingString:ImagePath] contents:data attributes:nil];
//得到选择后沙盒中图片的完整路径
filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,ImagePath];
return filePath;
}
网友评论