項目中需要將UIImage圖片保存為JPG圖片,iOS中提供了這樣的實現(xiàn)方法
UIImage *getImage = [UIImage imageWithContentsOfFile:file];
NSData *data;
if (UIImagePNGRepresentation(getImage) == nil){
data = UIImageJPEGRepresentation(getImage, 1);
} else {
data = UIImagePNGRepresentation(getImage);
}
其中UIImageJPEGRepresentation函數(shù)需要兩個參數(shù):圖片的引用和壓縮系數(shù)
而且默認(rèn)情況下UIImageJPEGRepresentation返回的數(shù)據(jù)大小也要比UIImagePNGRepresentation小很多
如果要返回第一個圖片地址楣富,可以把圖片保存到本地后,在輸出圖片地址:
//照片獲取本地路徑轉(zhuǎn)換
-(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];
//把剛剛圖片轉(zhuǎn)換的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;
}