浅析GIF 格式图片的存储与解析
haoteby 2024-11-25 12:41 2 浏览
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);
}
相关推荐
- 网站seo该怎么优化
-
一、网站定位在建设一个网站之前,我们首先要做的就是一个网站清晰的定位,会带来转化率相对较高的客户群体,我们建站的目的就是为了营销,只有集中来做某一件事,才会更好的展现我们的网站。在做SEO优化的同时...
- 3个小技巧教你如何做好SEO优化
-
想半路出家做SEO?可是,怎么才做的好呢?关于SEO专业技术弄懂搜索引擎原理,咱们做搜索引擎排名的首先就是要了解搜索引擎的工作原理,对SEO优化有更深入了解之后再来做SEO,你就能从搜索引擎的视点...
- SEO指令分享:filetype指令
-
filetype用于搜索特定的文件格式。百度和谷歌都支持filetype指令。比如搜索filetype:pdf今日头条返回的就是包含今日头条这个关键词的所有pdf文件,如下图:百度只支持:pdf...
- 网站seo优化技巧大全
-
SEO在搜索引擎中对检索结果进行排序,看谁最初是在用户的第一眼中看到的。实际上,这些排名都是通过引擎的内部算法来实现的。例如,百度算法很有名。那么,对百度SEO的优化有哪些小技巧?下面小编就会说下针对...
- 小技巧#10 某些高级的搜索技巧
-
由于某些原因,我的实验场所仅限百度。1.关键词+空格严格说来这个不能算高级,但关键词之间打空格的办法确实好用。我习惯用右手大拇指外侧敲击空格键,这个习惯在打英文报告时尤其频繁。2.site:(请不要忽...
- MYSQL数据库权限与安全
-
权限与安全数据库的权限和数据库的安全是息息相关的,不当的权限设置可能会导致各种各样的安全隐患,操作系统的某些设置也会对MySQL的安全造成影响。1、权限系统的工作原理...
- WPF样式
-
UniformGrid容器<UniformGridColumns="3"Rows="3"><Button/>...
- MySQL学到什么程度?才有可以在简历上写精通
-
前言如今互联网行业用的最多就是MySQL,然而对于高级Web面试者,尤其对于寻找30k下工作的求职者,很多MySQL相关知识点基本都会涉及,如果面试中,你的相关知识答的模糊和不切要点,基...
- jquery的事件名称和命名空间的方法
-
我们先看一些代码:当然,我们也可以用bind进行事件绑定。我们看到上面的代码,我们可以在事件后面,以点号,加我们的名字,就是事件命名空间。所谓事件命名空间,就是事件类型后面以点语法附加一个别名,以便引...
- c#,委托与事件,发布订阅模型,观察者模式
-
什么是事件?事件(Event)基本上说是一个用户操作,如按键、点击、鼠标移动等等,或者是一些提示信息,如系统生成的通知。应用程序需要在事件发生时响应事件。通过委托使用事件事件在类中声明且生成,且通过...
- 前端分享-原生Popover已经支持
-
传统网页弹窗开发需要自己处理z-index层级冲突、编写点击外部关闭的逻辑、管理多个弹窗的堆叠顺序。核心优势对比:...
- Axure 8.0 综合帖——新增细节内容
-
一、钢笔工具与PS或者AI中的钢笔工具一样的用法。同样有手柄和锚点,如果终点和起点没有接合在一起,只要双击鼠标左键即可完成绘画。画出来的是矢量图,可以理解为新的元件。不建议通过这个工具来画ICON图等...
- PostgreSQL技术内幕28:触发器实现原理
-
0.简介在PostgreSQL(简称PG)数据库中,触发器(Trigger)能够在特定的数据库数据变化事件(如插入、更新、删除等)或数据库事件(DDL)发生时自动执行预定义的操作。触发器的实现原理涉及...
- UWP开发入门(十七)--判断设备类型及响应VirtualKey
-
蜀黍我做的工作跟IM软件有关,UWP同时会跑在电脑和手机上。电脑和手机的使用习惯不尽一致,通常我倾向于根据窗口尺寸来进行布局的变化,但是特定的操作习惯是依赖于设备类型,而不是屏幕尺寸的,比如聊天窗口的...