起初看到這個功能我是拒絕的,之前做的視頻上傳都是獲取特定的幀數當封面拼余,沒有刻意的去選擇封面污桦,但是需求已定,隨后網上也找了下匙监,沒有類似的凡橱,于是乎就自己寫了一個,有什么改進的地方可以互相交流亭姥,話不多說直接上代碼了
1.打開相冊稼钩,系統(tǒng)相冊用的很順手,所以一直就用系統(tǒng)的相冊
//兩個代理
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *coverImageView;
@end
//代理方法
//打開相冊
- (void)openImagePickerController:(UIImagePickerControllerSourceType)type
{
if (![UIImagePickerController isSourceTypeAvailable:type]) return;
UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
//視頻最大時間
ipc.videoMaximumDuration = 30;
ipc.view.backgroundColor = [UIColor whiteColor];
ipc.sourceType = type;
ipc.delegate = self;
//只打開視頻
ipc.mediaTypes = @[(NSString *)kUTTypeMovie];
//視頻上傳質量
ipc.videoQuality = UIImagePickerControllerQualityTypeHigh;
[self presentViewController:ipc animated:YES completion:nil];
}
#pragma mark - UIImagePickerControllerDelegate
/**
* 從UIImagePickerController選擇完圖片后就調用(拍照完畢或者選擇相冊圖片完畢)
*/
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
CZHWeakSelf(self);
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
//如果是視頻
NSURL *url = info[UIImagePickerControllerMediaURL];
//計算相冊視頻時長
NSDictionary *videoDic = [CZHTool getLocalVideoSizeAndTimeWithSourcePath:url.absoluteString];
int videoTime = [[videoDic valueForKey:@"duration"] intValue];
//視頻限制的長度
NSUInteger limitTime = 30;
if (videoTime > limitTime) {
[picker dismissViewControllerAnimated:YES completion:nil];
return;
}
//把系統(tǒng)相冊mov格式轉換成mp4格式
[CZHTool convertMovTypeIntoMp4TypeWithSourceUrl:url convertSuccess:^(NSURL *path) {
CZHStrongSelf(self);
[picker dismissViewControllerAnimated:YES completion:nil];
//選擇封面控制器
CZHChooseCoverController *chooseCover = [[CZHChooseCoverController alloc] init];
//本地路徑
chooseCover.videoPath = path;
//選擇封面的block达罗,把封面image回調
chooseCover.coverImageBlock = ^(UIImage *coverImage) {
self.coverImageView.image = coverImage;
//上傳視頻操作
//[self changeWithUploadSource:path];
//上傳封面操作
//[self uploadCoverWithImage:coverImage];
};
[self presentViewController:chooseCover animated:YES completion:nil];
}];
}
}
// 取消圖片選擇調用此方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
// dismiss UIImagePickerController
[self dismissViewControllerAnimated:YES completion:nil];
}
2.選擇封面控制器
//截取幾張圖片放在底部用作展示坝撑,我是用collectionview做展示
AVURLAsset * asset = [AVURLAsset assetWithURL:self.videoPath];
CMTime? time = [asset duration];
self.timeValue = time.value;
self.timeScale = time.timescale;
if (time.value < 1) {
[self dismissViewControllerAnimated:YES completion:nil];
return;
}
NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:self.videoPath options:opts];
AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
generator.appliesPreferredTrackTransform = YES;
//總幀數/展示的總數量
long long baseCount = time.value / PHOTP_COUNT;
//取出PHOTP_COUNT張圖片,存放到數組,用于collectionview
for (NSInteger i = 0 ; i < PHOTP_COUNT; i++) {
NSError *error = nil;
//每隔baseCount幀取一幀存起來,一共PHOTP_COUNT張
CGImageRef img = [generator copyCGImageAtTime:CMTimeMake(i * baseCount, time.timescale) actualTime:NULL error:&error];
{
UIImage *image = [UIImage imageWithCGImage:img];
[self.photoArrays addObject:image];
}
}
//把存的存的幾張圖片用collectionview展示出來
CGRect collectionViewF = CGRectMake(0,? CZH_ScaleHeight(461), ScreenWidth, CZH_ScaleHeight(62.5));
UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:collectionViewF collectionViewLayout:layout];
collectionView.dataSource = self;
collectionView.backgroundColor = [UIColor clearColor];
[collectionView registerClass:[CZHChooseCoverCell class] forCellWithReuseIdentifier:ID];
[self.view addSubview:collectionView];
self.collectionView? = collectionView;
//在collectionview上面覆蓋一個slider用于滑動選擇圖片
UIImage *selected = [UIImage imageNamed:@"slider_select"];
UIImage *deselected = [UIImage imageNamed:@"slider_deselect"];
UISlider *slider = [[UISlider alloc] init];
slider.frame = CGRectMake(0,? CZH_ScaleHeight(461), ScreenWidth, CZH_ScaleHeight(62.5));
[slider setThumbImage:deselected forState:UIControlStateNormal];
[slider setThumbImage:selected forState:UIControlStateHighlighted];
//透明的圖片
UIImage *image = [CZHTool imageWithColor:[UIColor clearColor] size:CGSizeMake(1, 1)];
[slider setMinimumTrackImage:image forState:UIControlStateNormal];
[slider setMaximumTrackImage:image forState:UIControlStateNormal];
slider.maximumValue = self.timeValue;
slider.minimumValue = 0;
[slider addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:slider];
//默認選取第一幀展示
[self chooseWithTime:0];
//滑動slider的操作
- (void)valueChange:(UISlider *)sender {
int timeValue = sender.value;
[self chooseWithTime:timeValue];
}
- (void)chooseWithTime:(CMTimeValue)time {
NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:self.videoPath options:opts];
AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
generator.appliesPreferredTrackTransform = YES;
//? ? generator.maximumSize = CGSizeMake(ScreenWidth, ScreenHeight);
NSError *error = nil;
CGImageRef img = [generator copyCGImageAtTime:CMTimeMake(time, self.timeScale) actualTime:NULL error:&error];
{
UIImage *image = [UIImage imageWithCGImage:img];
self.imageView.image = image;
}
}
//點擊返回按鈕和完成按鈕的操作
- (void)buttonClick:(UIButton *)sender {
if (sender.tag == CZHChooseCoverControllerButtonTypeBack) {
[self dismissViewControllerAnimated:YES completion:nil];
} else if (sender.tag == CZHChooseCoverControllerButtonTypeComplete) {
//封面圖片回調
if (_coverImageBlock) {
_coverImageBlock(self.imageView.image);
}
[self dismissViewControllerAnimated:YES completion:nil];
}
}
ps.模擬器相冊沒有視頻的話可以用下面代碼把項目的視頻保存到相冊
NSMutableArray *videoArray = [NSMutableArray array];
//工程中類型是MP4的文件數組
NSArray *movs = [[NSBundle mainBundle] pathsForResourcesOfType:@"mp4" inDirectory:nil];
[videoArray addObjectsFromArray:movs];
for (id item in videoArray) {
//循環(huán)保存到相冊
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(item)) {
UISaveVideoAtPathToSavedPhotosAlbum(item, self, nil, NULL);
}
}