如何从ALAssetRepresentation创建有效的CGImageSourceRef?

问题描述 投票:8回答:4

我正在尝试使用CGImageSourceCreateThumbnailAtIndex来有效地创建图像的大小调整版本。我有一些现有的代码用磁盘上的图像来做这件事,现在我正在尝试使用来自ALAssetsLibrary的图像。

这是我的代码:

ALAsset *asset;
ALAssetRepresentation *representation = [asset defaultRepresentation];
CGImageRef imageRef = [representation fullResolutionImage];

CGDataProviderRef provider = CGImageGetDataProvider(imageRef);
CGImageSourceRef sourceRef = CGImageSourceCreateWithDataProvider(provider, NULL);

NSDictionary *resizeOptions = @{
  kCGImageSourceCreateThumbnailWithTransform : @YES,
  kCGImageSourceCreateThumbnailFromImageAlways : @YES,
  kCGImageSourceThumbnailMaxPixelSize : @(2100) 
};

CGImageRef resizedImage = CGImageSourceCreateThumbnailAtIndex(source, 0, resizeOptions);

问题是resizedImage为null,CGImageSourceGetCount(sourceRef)返回0.但数据提供者确实有相当多的数据,并且数据似乎确实是有效的图像数据。 ALAsset来自iPhone 4S相机胶卷。

我错过了什么?为什么CGImageSourceCreateWithDataProvider()会创建一个包含0张图像的图像源?

core-graphics alassetslibrary alasset
4个回答
4
投票

CGImageSource用于反序列化序列化图像,例如JPEG,PNG和诸如此类的图像。

CGImageGetDataProvider返回图像的原始像素数据(提供者)。它不会以某种外部格式返回序列化字节。 CGImageSource无法知道任何给定原始像素数据所在的像素格式(颜色空间,每个组件的位数,alpha布局等)。

您可以尝试获取资产代表的URL并将其提供给CGImageSourceCreateWithURL。如果这不起作用(例如,不是文件URL),则必须通过CGImageDestination运行图像,并在输出输出的任何位置创建CGImageSource。

(尝试另外一件事就是看看代表的filename是否真的是一条完整的路径,Cocoa经常滥用这个词的方式。但你可能不应该依赖它。)


2
投票

你可能尝试的一件事是the asset rep's CGImageWithOptions: method

该文件声称:

此方法返回可用的最大,最佳表示,不以任何方式调整。

但它也说关于fullResolutionImage,我不知道为什么这个类如果它们都做同样的事情会有这两种方法。我想知道它是否是一个复制粘贴错误。

尝试CGImageWithOptions:与一堆缩略图创建选项,看看会发生什么。


1
投票

选项#3将是代表的fullScreenImage。根据您需要的“缩略图”类型,使用它可能更便宜和/或更简单,这将不会大于(大约)设备屏幕的大小。


0
投票

这也可以帮助......

ALAssetRepresentation* rep = [asset defaultRepresentation];

NSDictionary* options = [[NSDictionary alloc] initWithObjectsAndKeys:
                     (id)kCFBooleanTrue, (id)kCGImageSourceCreateThumbnailWithTransform,
                     (id)kCFBooleanTrue, (id)kCGImageSourceCreateThumbnailFromImageAlways, 
                     (id)[NSNumber numberWithDouble:400], (id)kCGImageSourceThumbnailMaxPixelSize, 
                     nil];

CGImageRef image = [rep CGImageWithOptions:options];
© www.soinside.com 2019 - 2024. All rights reserved.