保存图片
使用UIImageWriteToSavedPhotosAlbum
方法保存图片到相册
- (void)saveImage:(UIImage *)image {
UIImageWriteToSavedPhotosAlbum(image, self,
@selector(UIImageWriteToSavedPhotosAlbum_image:didFinishSavingWithError:contextInfo:), nil);
}
- (void)UIImageWriteToSavedPhotosAlbum_image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
if (error) {
NSLog(@"UIImageWriteToSavedPhotosAlbum_image %@", error);
} else {
NSLog(@"UIImageWriteToSavedPhotosAlbum_image success");
}
}
使用ALAssetsLibrary
框架保存图片到相册
- (void)saveAssetLibraryImage:(UIImage *)image {
ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
[lib writeImageToSavedPhotosAlbum:image.CGImage metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
if (error) {
NSLog(@"saveAssetLibraryImage %@", error);
} else {
NSLog(@"saveAssetLibraryImage success");
}
}];
}
使用PHPhoto
框架保存图片到相册
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
[PHAssetChangeRequest creationRequestForAssetFromImage:image];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
if (error) {
NSLog(@"savePhotoLibraryImage %@", error);
} else {
NSLog(@"savePhotoLibraryImage success");
}
}];
保存视频
使用UISaveVideoAtPathToSavedPhotosAlbum
方法保存图片到相册
- (void)saveVideo:(NSURL *)mediaURL {
UISaveVideoAtPathToSavedPhotosAlbum([mediaURL path], self,
@selector(UISaveVideoAtPathToSavedPhotosAlbum_videoPath:didFinishSavingWithError:contextInfo:), nil);
}
- (void)UISaveVideoAtPathToSavedPhotosAlbum_videoPath:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
if (error) {
NSLog(@"UISaveVideoAtPathToSavedPhotosAlbum_videoPath %@", error);
} else {
NSLog(@"UISaveVideoAtPathToSavedPhotosAlbum_videoPath success");
}
}
使用ALAssetsLibrary
框架保存视频到相册
- (void)saveAssetLibraryVideo:(NSURL *)mediaURL {
ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
[lib writeVideoAtPathToSavedPhotosAlbum:mediaURL completionBlock:^(NSURL *assetURL, NSError *error) {
if (error) {
NSLog(@"saveAssetLibraryVideo %@", error);
} else {
NSLog(@"saveAssetLibraryVideo success");
}
}];
}
使用PHPhoto
框架保存视频到相册
- (void)savePhotoLibraryVideo:(NSURL *)mediaURL {
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
[PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:mediaURL];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
if (error) {
NSLog(@"savePhotoLibraryVideo %@", error);
} else {
NSLog(@"savePhotoLibraryVideo success");
}
}];
}
权限
需要在Info.plist文件中,添加权限
图片压缩
iOS自带压缩方法UIImageJPEGRepresentation
- (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)maxSize {
NSData * data = UIImageJPEGRepresentation(image, 1.0);
CGFloat dataKBytes = data.length;
CGFloat maxQuality = 1.0f;
while (dataKBytes > maxSize && maxQuality > 0.1f) {
maxQuality = maxQuality - 0.1f;
data = UIImageJPEGRepresentation(image, maxQuality);
dataKBytes = data.length;
}
return data;
}