浅析GIF 格式图片的存储与解析
haoteby 2024-11-25 12:41 21 浏览
GIF ( Graphics Interchange Format )原义是“图像互换格式”,是 CompuServe 公司在1987年开发出的图像文件格式,可以说是互联网界的老古董了。
GIF 格式可以存储多幅彩色图像,如果将这些图像连续播放出来,就能够组成最简单的动画。所以常被用来存储“动态图片”,通常时间短,体积小,内容简单,成像相对清晰。
GIF存储格式
一个GIF文件主要由以下几部分组成:
- 文件头
- 图像帧信息
- 注释
(1)文件头
GIF格式文件头和一般文件头差别不大,也包含有:
- 格式声明
- 逻辑屏幕描述块
- 全局调色盘
格式声明
Signature 为“GIF”3 个字符;Version 为“87a”或“89a”3 个字符。
逻辑屏幕描述块
前两字节为像素单位的宽、高,用以标识图片的视觉尺寸。
Packet里是调色盘信息,分别来看:
Global Color Table Flag为全局颜色表标志,即为1时表明全局颜色表有定义。
Color Resolution 代表颜色表中每种基色位长(需要+1),为111时,每个颜色用8bit表示,即我们熟悉的RGB表示法,一个颜色三字节。
Sort Flag 表示是否对颜色表里的颜色进行优先度排序,把常用的排在前面,这个主要是为了适应一些颜色解析度低的早期渲染器,现在已经很少使用了。
Global Color Table 表示颜色表的长度,计算规则是值+1作为2的幂,得到的数字就是颜色表的项数,取最大值111时,项数=256,也就是说GIF格式最多支持256色的位图,再乘以Color Resolution算出的字节数,就是调色盘的总长度。
这四个字段一起定义了调色盘的信息。
Background color Index 定义了图像透明区域的背景色在调色盘里的索引。
Pixel Aspect Ratio 定义了像素宽高比,一般为0。
(2)帧信息描述
帧信息描述就是每一帧的图像信息和相关标志位,直观地说,帧信息应该由一系列的点阵数据组成,点阵中存储着一系列的颜色值。点阵数据本身的存储也是可以进行压缩的,GIF图所采用的是LZW压缩算法。
这是ImageMagick官方范例里的一张GIF图。
根据直观感受,这张图片的每一帧应该是这样的。
但实际上,进行过压缩优化的图片,每一帧是这样的。
首先,对于各帧之间没有变化的区域进行了排除,避免存储重复的信息。
其次,对于需要存储的区域做了透明化处理,只存储有变化的像素,没变化的像素只存储一个透明值。
我们再来看帧信息的具体定义,主要包括:
- 帧分隔符
- 帧数据说明
- 点阵数据(它存储的不是颜色值,而是颜色索引)
- 帧数据扩展(只有89a标准支持)
1和3比较直观,第二部分和第四部分则是一系列的标志位,定义了对于“帧”需要说明的内容。
帧数据说明。
除了上面说过的字段之外,还多了一个Interlace Flag,表示帧点阵的存储方式,有两种,顺序和隔行交错,为 1 时表示图像数据是以隔行方式存放的。最初 GIF 标准设置此标志的目的是考虑到通信设备间传输速度不理想情况下,用这种方式存放和显示图像,就可以在图像显示完成之前看到这幅图像的概貌,慢慢的变清晰,而不觉得显示时间过长。
帧数据扩展是89a标准增加的,主要包括四个部分。
1、程序扩展结构(Application Extension)主要定义了生成该gif的程序相关信息
2、注释扩展结构(Comment Extension)一般用来储存图片作者的签名信息
3、图形控制扩展结构(Graphic Control Extension)这部分对图片的渲染比较重要
除了前面说过的Dispose Method、Delay、Background Color之外,User Input用来定义是否接受用户输入后再播放下一帧,需要图像解码器对应api的配合,可以用来实现一些特殊的交互效果。
4、平滑文本扩展结构(Plain Text Control Extension)
89a标准允许我们将图片上的文字信息额外储存在扩展区域里,但实际渲染时依赖解码器的字体环境,所以实际情况中很少使用。
以上扩展块都是可选的,只有Label置位的情况下,解码器才会去渲染
Glide 加载Gif原理
Glide 解析Gif文件格式代码:
/**
* Reads GIF file header information.
*/
private void readHeader() {
StringBuilder id = new StringBuilder();
for (int i = 0; i < 6; i++) {
id.append((char) read());
}
if (!id.toString().startsWith("GIF")) {
header.status = STATUS_FORMAT_ERROR;
return;
}
}
/**
* Reads Logical Screen Descriptor.
*/
private void readLSD() {
// Logical screen size.
header.width = readShort();
header.height = readShort();
/*
* Logical Screen Descriptor packed field:
* 7 6 5 4 3 2 1 0
* +---------------+
* 4 | | | | |
*
* Global Color Table Flag 1 Bit
* Color Resolution 3 Bits
* Sort Flag 1 Bit
* Size of Global Color Table 3 Bits
*/
int packed = read();
header.gctFlag = (packed & LSD_MASK_GCT_FLAG) != 0;
header.gctSize = (int) Math.pow(2, (packed & LSD_MASK_GCT_SIZE) + 1);
// Background color index.
header.bgIndex = read();
// Pixel aspect ratio
header.pixelAspect = read();
}
/**
* Reads color table as 256 RGB integer values.
*
* @param nColors int number of colors to read.
* @return int array containing 256 colors (packed ARGB with full alpha).
*/
@Nullable
private int[] readColorTable(int nColors) {
int nBytes = 3 * nColors;
int[] tab = null;
byte[] c = new byte[nBytes];
try {
rawData.get(c);
// TODO: what bounds checks are we avoiding if we know the number of colors?
// Max size to avoid bounds checks.
tab = new int[MAX_BLOCK_SIZE];
int i = 0;
int j = 0;
while (i < nColors) {
int r = ((int) c[j++]) & MASK_INT_LOWEST_BYTE;
int g = ((int) c[j++]) & MASK_INT_LOWEST_BYTE;
int b = ((int) c[j++]) & MASK_INT_LOWEST_BYTE;
tab[i++] = 0xFF000000 | (r << 16) | (g << 8) | b;
}
} catch (BufferUnderflowException e) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Format Error Reading Color Table", e);
}
header.status = STATUS_FORMAT_ERROR;
}
return tab;
}
/**
* Reads next frame image.
*/
private void readBitmap() {
// (sub)image position & size.
header.currentFrame.ix = readShort();
header.currentFrame.iy = readShort();
header.currentFrame.iw = readShort();
header.currentFrame.ih = readShort();
/*
* Image Descriptor packed field:
* 7 6 5 4 3 2 1 0
* +---------------+
* 9 | | | | | |
*
* Local Color Table Flag 1 Bit
* Interlace Flag 1 Bit
* Sort Flag 1 Bit
* Reserved 2 Bits
* Size of Local Color Table 3 Bits
*/
int packed = read();
boolean lctFlag = (packed & DESCRIPTOR_MASK_LCT_FLAG) != 0;
int lctSize = (int) Math.pow(2, (packed & DESCRIPTOR_MASK_LCT_SIZE) + 1);
header.currentFrame.interlace = (packed & DESCRIPTOR_MASK_INTERLACE_FLAG) != 0;
if (lctFlag) {
header.currentFrame.lct = readColorTable(lctSize);
} else {
// No local color table.
header.currentFrame.lct = null;
}
// Save this as the decoding position pointer.
header.currentFrame.bufferFrameStart = rawData.position();
// False decode pixel data to advance buffer.
skipImageData();
if (err()) {
return;
}
header.frameCount++;
// Add image to frame.
header.frames.add(header.currentFrame);
}
Glide渲染Gif主要是通过GifDrawable这个类,该类实现了Animatable接口,当调用start()方法后开始循环播放,在draw()方法里进行绘制bitmap。
@Override
public void start() {
isStarted = true;
resetLoopCount();
if (isVisible) {
startRunning();
}
}
private void startRunning() {
// 当 Gif 只有一帧的时候,会直接调用绘制方法
if (state.frameLoader.getFrameCount() == 1) {
invalidateSelf();
} else if (!isRunning) {
isRunning = true;
// Gif 不止一帧的时候,就开启了订阅
state.frameLoader.subscribe(this);
invalidateSelf();
}
}
@Override
public void draw(@NonNull Canvas canvas) {
if (isRecycled) {
return;
}
if (applyGravity) {
Gravity.apply(GRAVITY, getIntrinsicWidth(), getIntrinsicHeight(), getBounds(), getDestRect());
applyGravity = false;
}
Bitmap currentFrame = state.frameLoader.getCurrentFrame();
canvas.drawBitmap(currentFrame, null, getDestRect(), getPaint());
}
Gif图片中的每一帧的bitmap就是GifFrameLoader里GifDecoder解析出来的,GifDrawable调用start()方法后,会在GifFrameLoader注册监听,每一帧图片解析完后会回调再进行绘制
void subscribe(FrameCallback frameCallback) {
if (isCleared) {
throw new IllegalStateException("Cannot subscribe to a cleared frame loader");
}
if (callbacks.contains(frameCallback)) {
throw new IllegalStateException("Cannot subscribe twice in a row");
}
boolean start = callbacks.isEmpty();
callbacks.add(frameCallback);
if (start) {
start();
}
}
start() {
loadNextFrame();
}
private void loadNextFrame() {
if (!isRunning || isLoadPending) {
return;
}
if (startFromFirstFrame) {
Preconditions.checkArgument(
pendingTarget == null, "Pending target must be null when starting from the first frame");
gifDecoder.resetFrameIndex();
startFromFirstFrame = false;
}
if (pendingTarget != null) {
DelayTarget temp = pendingTarget;
pendingTarget = null;
onFrameReady(temp);
return;
}
isLoadPending = true;
// Get the delay before incrementing the pointer because the delay indicates the amount of time
// we want to spend on the current frame.
int delay = gifDecoder.getNextDelay();
long targetTime = SystemClock.uptimeMillis() + delay;
gifDecoder.advance();
next = new DelayTarget(handler, gifDecoder.getCurrentFrameIndex(), targetTime);
requestBuilder.apply(signatureOf(getFrameSignature())).load(gifDecoder).into(next);
}
Glide 加载 Gif 的原理比较简单,就是将 Gif 解码成多张图片进行无限轮播,每帧切换都是一次图片加载请求,再加载到新的一帧数据之后会对旧的一帧数据进行清除,然后再继续下一帧数据的加载请求,以此类推,使用 Handler 发送消息实现循环播放。
android-gif-drawable
也是用sdk内部的Gifdrawable来进行渲染的,与glide类似,该类也是继承了Animatable接口,在适当的时候调用start()方法就会开始循环绘制,然后在draw()方法里进行bitmap绘制
/**
* Starts the animation. Does nothing if GIF is not animated.
* This method is thread-safe.
*/
@Override
public void start() {
synchronized (this) {
if (mIsRunning) {
return;
}
mIsRunning = true;
}
final long lastFrameRemainder = mNativeInfoHandle.restoreRemainder();
startAnimation(lastFrameRemainder);
}
void startAnimation(long lastFrameRemainder) {
if (mIsRenderingTriggeredOnDraw) {
mNextFrameRenderTime = 0;
mInvalidationHandler.sendEmptyMessageAtTime(MSG_TYPE_INVALIDATION, 0);
} else {
cancelPendingRenderTask();
mRenderTaskSchedule = mExecutor.schedule(mRenderTask, Math.max(lastFrameRemainder, 0), TimeUnit.MILLISECONDS);
}
}
public void draw(@NonNull Canvas canvas) {
final boolean clearColorFilter;
if (mTintFilter != null && mPaint.getColorFilter() == null) {
mPaint.setColorFilter(mTintFilter);
clearColorFilter = true;
} else {
clearColorFilter = false;
}
if (mTransform == null) {
canvas.drawBitmap(mBuffer, mSrcRect, mDstRect, mPaint);
} else {
mTransform.onDraw(canvas, mPaint, mBuffer);
}
if (clearColorFilter) {
mPaint.setColorFilter(null);
}
}
与glide不同的是,android-gif-drawable的bitmap解析是在native层进行的,并且Bitmap对象只会存在一个
Java_pl_droidsonroids_gif_GifInfoHandle_renderFrame(JNIEnv *env, jclass __unused handleClass, jlong gifInfo, jobject jbitmap) {
GifInfo *info = (GifInfo *) (intptr_t) gifInfo;
if (info == NULL)
return -1;
long renderStartTime = getRealTime();
void *pixels;
if (lockPixels(env, jbitmap, info, &pixels) != 0) {
return 0;
}
DDGifSlurp(info, true, false);
if (info->currentIndex == 0) {
prepareCanvas(pixels, info);
}
const uint_fast32_t frameDuration = getBitmap(pixels, info);
unlockPixels(env, jbitmap);
return calculateInvalidationDelay(info, renderStartTime, frameDuration);
}
相关推荐
- 如何随时清理浏览器缓存_清理浏览器缓存怎么弄
-
想随时清理浏览器缓存吗?Cookieformac版是Macos上一款浏览器缓存清理工具,所有的浏览器Cookie,本地存储数据,HTML5数据库,FlashCookie,Silverlight,...
- Luminati代理动态IP教程指南配置代理VMLogin中文版反指纹浏览器
-
介绍如何使用在VMLogin中文版设置Luminati代理。首先下载VMLogin中文版反指纹浏览器(https://cn.vmlogin.com)对于刚接触Luminati动态ip的朋友,是不是不懂...
- mac清除工具分享,解除您在安全方面的后顾之忧
-
想要永久的安全的处理掉重要数据,删除是之一,使用今天小编分享的mac清除工具,为您的操作再增一层“保护”,小伙伴慎用哟,一旦使用就不可以恢复咯,来吧一起看看吧~mac清除工具分享,解除您在安全方面的后...
- 取代cookie的网站追踪技术:”帆布指纹识别”
-
【前言】一般情况下,网站或者广告联盟都会非常想要一种技术方式可以在网络上精确定位到每一个个体,这样可以通过收集这些个体的数据,通过分析后更加精准的去推送广告(精准化营销)或其他有针对性的一些活动。Co...
- 辅助上网为啥会被抛弃 曲奇(Cookie)虽甜但有毒
-
近期有个小新闻,大概很多小伙伴都没有注意到,那就是谷歌Chrome浏览器要弃用Cookie了!说到Cookie功能,很多小伙伴大概觉得不怎么熟悉,有可能还不如前一段时间被弃用的Flash“出名”,但它...
- 浏览器指纹是什么?浏览器指纹包括哪些信息
-
本文关键词:浏览器指纹、指纹浏览器、浏览器指纹信息、指纹浏览器原理什么是浏览器指纹?浏览器指纹是指浏览器的各种信息,当我们访问其他网站时,即使是在匿名的模式下,这些信息也可以帮助网站识别我们的身份。...
- 那些通用清除软件不曾注意的秘密_清理不常用的应用软件
-
系统清理就像卫生检查前的大扫除,即使你使出吃奶的劲儿把一切可能的地方都打扫过,还会留下边边角角的遗漏。随着大家电脑安全意识的提高,越来越多的朋友开始关注自己的电脑安全,也知道安装360系列软件来"武装...
- 「网络安全宣传周」这些安全上网小知识你要知道!
-
小布说:互联网改变了人们的衣食住行,但与之伴生的网络安全威胁也不容忽视。近些年来,风靡全球的勒索病毒、时有发生的电信诈骗、防不胜防的个人信息泄露时时刻刻都威胁着我们的生活。9月18日-24日是第四届...
- TypeScript 终极初学者指南_typescript 进阶
-
在过去的几年里TypeScript变得越来越流行,现在许多工作都要求开发人员了解TypeScript...
- jQuery知识一览_jquery的认识和使用
-
一、概览jQuery官网:https://jquery.com/jQuery是一个高效、轻量并且功能丰富的js库。核心在于查询query。...
- 我的第一个Electron应用_electronmy
-
hello,好久不见,最近笔者花了几天时间入门Electron,然后做了一个非常简单的应用,本文就来给各位分享一下过程,Electron大佬请随意~笔者开源了一个Web思维导图,虽然借助showSav...
- HTML5 之拖放(Drag 和 Drop)_html拖放api
-
简介拖放是一种常见的特性,即抓取对象以后拖到另一个位置。在HTML5中,拖放是标准的一部分,任何元素都能够拖放。先点击一个小例子:在用户开始拖动<p>元素时执行JavaScrip...
- 如何用JavaScript判断输入值是数字还是字母?
-
在日常开发中,我们有时候需要判断用户输入的是数字还是字母。本文将介绍如何用JavaScript实现这一功能。检查输入值是否是数字或字母...
- 图形编辑器开发:快捷键的管理_图形编辑工具
-
大家好,我是前端西瓜哥。...
- 浏览器原生剪贴板:原来它能这样读取用户截图!
-
当我们使用GitHub时,会发现Ctrl+V就能直接读取用户剪贴板图片进行粘贴,那么它是如何工作的?安全性如何?...