从用户库保存/获取JPEG,无需重新压缩
我试图find一种方法来读取和写入JPEG图像到用户库(相机胶卷),而无需iOS重新压缩它们。 UIImage似乎是这里的瓶颈。 保存到用户库唯一的方法,我发现是UIImageWriteToSavedPhotosAlbum()。 有没有解决的办法?
现在我的例程看起来像这样
– 问一个照片的UIImagePickerController。 而当它做了FinishPickingMediaWithInfo,做:
NSData *imgdata = [NSData dataWithData:UIImageJPEGRepresentation([info objectForKey:@"UIImagePickerControllerOriginalImage"], 1)]; [imgdata writeToFile:filePath atomically:NO];
– 在磁盘上无损处理JPEG。
– 然后保存:
UIImageWriteToSavedPhotosAlbum([UIImage imageWithContentsOfFile:[self getImagePath]], self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
下面是一个小小的animation:3次传递后质量下降的样子:
每当我这样做的时候,显然会变得更糟,但是我无法自动完成图像采集部分,以便完全testing50/100/1000周期。
UIImage
解码图像数据,所以可以编辑和显示
UIImageWriteToSavedPhotosAlbum([UIImage imageWithContentsOfFile:[NSData dataWithContentsOfFile:[self getImagePath]]], self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
将首先解码图像,并将其编码回UIImageWriteToSavedPhotosAlbum
方法。
相反,你应该使用ALAssetsLibrary / writeImageDataToSavedPhotosAlbum:metadata:completionBlock:,像这样:
ALAssetsLibrary *assetLib = [[[ALAssetsLibrary alloc] init] autorelease]; [assetLib writeImageDataToSavedPhotosAlbum:[self getImagePath] metadata:nil completionBlock:nil];
您也可以将元数据和完成块传递给调用。
编辑:
为了获得图像:
[info objectForKey:@"UIImagePickerControllerOriginalImage"]
包含从UIImagePickerController
select的解码的UIImage
。 你应该改用
NSURL *assetURL = [info objectForKey:UIImagePickerControllerReferenceURL];
使用assetURL
您现在可以使用ALAssetsLibrary / assetForURL:resultBlock:failureBlock:方法为其获取ALAsset :
ALAssetsLibrary *assetLib = [[[ALAssetsLibrary alloc] init] autorelease]; [assetLib assetForURL:assetURL resultBlock:resultBlock failureBlock:failureBlock];
你现在可以得到该图像的未改变的NSData:
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *asset){ ALAssetRepresentation *assetRep = [asset defaultRepresentation]; long long imageDataSize = [assetRepresentation size]; uint8_t* imageDataBytes = malloc(imageDataSize); [assetRepresentation getBytes:imageDataBytes fromOffset:0 length:imageDataSize error:nil]; NSData *imageData = [NSData dataWithBytesNoCopy:imageDataBytes length:imageDataSize freeWhenDone:YES]; // you could for instance read data in smaller buffers and append them to your file instead of reading it all at once // save it [imgdata writeToFile:filePath atomically:NO]; }; ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror){ NSLog(@"Cannot get image - %@",[myerror localizedDescription]); // };
我可能在代码中犯了一些错误,但步骤如上所列。 如果某些东西不能正常工作,或者希望使其效率更高一些,那么可以使用大量的例子来做一些事情,比如从ALAsset
读取NSData
中的ALAsset
。