QLThumbnailGenerationRequest无法从iPhone相机拍摄图生成缩略图求助
解决QLThumbnailGenerationRequest无法从相机拍摄图片生成缩略图的问题
问题分析
你遇到的QLThumbnailErrorDomain Code=102错误对应QLThumbnailErrorUnsupportedDocumentType,说明缩略图生成器无法识别你保存的文件类型。核心原因是通过UIImageJPEGRepresentation转换并保存的图片丢失了原始图片的元数据,导致QL无法正确判定它为有效JPEG文件。
解决方案
方案一:直接使用相机返回的原始文件URL(推荐)
相机拍摄的图片会自动保存到系统临时目录,无需自行转换保存,直接从UIImagePickerController的info字典中获取原始文件URL即可:
// 从info字典获取相机拍摄的原始图片URL NSURL *originalImageURL = info[UIImagePickerControllerImageURL]; CGSize thumbnailSize = CGSizeMake(720, 720); QLThumbnailGenerator *generator = [[QLThumbnailGenerator alloc] init]; QLThumbnailGenerationRequest *request = [[QLThumbnailGenerationRequest alloc] initWithFileAtURL:originalImageURL size:thumbnailSize scale:[UIScreen mainScreen].scale representationTypes:QLThumbnailGenerationRequestRepresentationTypeThumbnail]; [generator generateBestRepresentationForRequest:request completionHandler:^(QLThumbnailRepresentation * _Nullable thumbnail, NSError * _Nullable error) { if (error) { NSLog(@"ERROR = %@", error.localizedDescription); } else { NSLog(@"SUCCESS"); // 获取生成的缩略图 UIImage *thumbnailImage = thumbnail.image; } }];
方案二:自行保存UIImage时添加正确的UTI标识
如果必须将UIImage转换为Data保存,需要在创建QLThumbnailGenerationRequest时手动指定文件的UTI(统一类型标识符),确保QL能识别文件类型:
UIImage *source = info[UIImagePickerControllerOriginalImage]; NSData *imageData = UIImageJPEGRepresentation(source, 1.0); NSString *directoryPath = NSTemporaryDirectory(); NSString *filePath = [directoryPath stringByAppendingPathComponent:@"CapturedImageFromCamera.jpg"]; NSError *error = nil; BOOL success = [imageData writeToFile:filePath options:NSDataWritingAtomic error:&error]; if (success) { CGSize thumbnailSize = CGSizeMake(720, 720); QLThumbnailGenerator *generator = [[QLThumbnailGenerator alloc] init]; // 手动指定文件UTI为JPEG类型 QLThumbnailGenerationRequest *request = [[QLThumbnailGenerationRequest alloc] initWithFileAtURL:[NSURL fileURLWithPath:filePath] size:thumbnailSize scale:[UIScreen mainScreen].scale UTI:(NSString *)kUTTypeJPEG representationTypes:QLThumbnailGenerationRequestRepresentationTypeThumbnail]; [generator generateBestRepresentationForRequest:request completionHandler:^(QLThumbnailRepresentation * _Nullable thumbnail, NSError * _Nullable error) { if (error) { NSLog(@"ERROR = %@", error.localizedDescription); } else { NSLog(@"SUCCESS"); } }]; }
注意:使用
kUTTypeJPEG需要导入MobileCoreServices框架:#import <MobileCoreServices/MobileCoreServices.h>
额外验证步骤
你可以在保存文件后,尝试用以下代码验证文件是否有效:
UIImage *testImage = [UIImage imageWithContentsOfFile:filePath]; if (!testImage) { NSLog(@"保存的图片文件损坏"); }
内容的提问来源于stack exchange,提问作者Adeel Ur Rehman
相关产品推荐
相关产品推荐

