我如何在iOS中生成24位真彩色GIFanimation?
我想要从base64string表示的几个PNG文件生成一个真正的彩色animationGIF。 我发现这个post,并做了类似的事情。 我有一个dataUrls数组:
NSArray* imageDataUrls; // array with the data urls without data:image/png;base64, prefix
这是我做的:
NSDictionary *fileProperties = @{ (__bridge id)kCGImagePropertyGIFDictionary: @{ (__bridge id)kCGImagePropertyGIFLoopCount: @0, // 0 means loop forever } }; NSDictionary *frameProperties = @{ (__bridge id)kCGImagePropertyGIFDictionary: @{ (__bridge id)kCGImagePropertyGIFDelayTime: @0.4f, // a float (not double!) in seconds, rounded to centiseconds in the GIF data } }; NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil]; NSURL *fileURL = [documentsDirectoryURL URLByAppendingPathComponent:@"animated.gif"]; CFMutableDataRef destinationData = CFDataCreateMutable(kCFAllocatorDefault, 0); CGImageDestinationRef destination = CGImageDestinationCreateWithData(destinationData, kUTTypeGIF, kFrameCount, NULL); CGImageDestinationSetProperties(destination, (__bridge CFDictionaryRef)fileProperties); NSData* myImageData; UIImage *myImage = [UIImage alloc]; for (NSUInteger i = 0; i < kFrameCount; i++) { @autoreleasepool { myImageData = [NSData dataFromBase64String:[imageDataUrls objectAtIndex:i]]; myImage = [myImage initWithData: myImageData]; CGImageDestinationAddImage(destination, myImage.CGImage, (__bridge CFDictionaryRef)frameProperties); } } myImageData = nil; myImage = nil; CFRelease(destination); NSData* data = nil; data = (__bridge NSData *)destinationData;
最后,我将gif图像作为base64EncodedString发送回phonegap容器。
// send back gif image CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString: [data base64EncodedString]];
它工作的很好,但是由此产生的gif图像的质量是不好的。 这是因为它只有256色。
这是原始的PNG图像:
以下是生成的gif图片的截图:
我如何获得与我导入的相同的质量,即如何提高生成的gif的质量水平? 如何在iOS上生成真正的GIF图像?
GIF并不是用来存储真彩色数据的,它们也不适合animation1 。 由于这是一个不寻常的使用GIF,你将不得不写很多自己的代码。
-
将每个帧分成矩形块,其中每个块最多包含256种不同的颜色。 最简单的方法是使用16×16块。
-
将每个块转换为索引图像。
-
将每个块添加到GIF。 对于帧中的第一个块,使用帧延迟。 对于帧中的其他块,使用延迟0。
完成。 您将不得不熟悉GIF规范,该规范可以在线免费获得( W3.org的GIF89a规范 ,请参阅第23节)。 你还需要find一个LZW压缩机,这不是很难find。 该animation还将使用一个下stream的存储量:包括base64转换,我估计大约43位/像素,或约1.2 Gbit / s的720pvideo,这是大约400倍的存储,你将用于高品质的MPEG4或WebM,可能大约是PNG存储容量的3倍。 对于主机和客户端来说,存储和带宽要求可能会带来不利的成本,除非animation非常短小。
请注意,这不会允许您使用Alpha透明度,这是GIF格式的一个硬性限制。
意见
在GIF中插入高质量的animation的想法是荒谬的,尽pipe这是可能的。 鉴于可用的替代scheme,这是特别荒谬的:
-
如果您针对的是现代浏览器或移动设备,MPEG4( 支持matrix )和WebM( 支持matrix )是明显的select。 在两种格式之间,只有Opera Mini不支持。
-
如果您的目标是旧版浏览器或function较差的设备,或者您无法承受MPEG4编码,则可以将帧编码为单独的JPEG或PNG图像。 按照时间对这些数据进行捆绑,并使用JavaScript或其他客户端脚本在animation帧之间进行切换。 这工作出奇的好。
笔记
1从GIF 89a规范 :
animation – graphics交换格式不是作为animation的平台,尽pipe它可以以有限的方式完成。