GIF文件学习

本文分享了在表情App项目中遇到的GIF图片处理问题及其解决方案,包括判断GIF格式、获取图片尺寸及帧间隔等实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.概述

最近参与的项目是一个和表情相关的App,也就理所当然的和GIF打交道了。下面就项目中遇到的和GIF相关的问题及解决办法分

享出来,第一次接触GIF,了解的不多,希望能和大家共同探讨学习。

本文学习参考博客:gif格式图片详细解析。


2.GIF简介

图像互换格式(GIF,Graphics Interchange Format)是一种位图图形文件格式,以8位色(即256种颜色)重现真彩色的图像。它实际
是一种压缩文档,采用LZW压缩算法进行编码,有效地减少了图像文件在网络上传输的时间。它是目前万维网广泛应用的网络传输图像格式之
一。想更多了解可参考:GIF-维基百科

3.GIF文件结构

如上图,GIF格式的文件结构整体上分为三部分:文件头、GIF数据流、文件结尾。文件头包含GIF文件署名和版本号;GIF

数据流由控制标识符、图象块和其他的一些扩展块组成;文件终结器只有一个值为0x3B的字符(';')表示文件结束。关于更多细节

可以参考博客:gif格式图片详细解析。

结合GIF文件格式理论知识,简单介绍一下我是如何通过解析或者处理GIF文件完成项目中实际的需求的。若有不对的地方或者

不够优化的方法欢迎提出,大家互相交流学习。项目中遇到的关GIF的需求较多,以下是三个较为常用的需求:

需求一:判断文件是否是GIF格式文件

需求二:获取GiF文件宽高属性

需求三:获取和修改GIF文件帧间隔


4.需求一 &GIF署名(Signature)和版本号(Version

`

如上图,GIF文件的前6个字节内容是GIF的署名和版本号。我们可以通过前3个字节判断文件是否为GIF格式,后3个字节判断

GIF格式的版本。

可以借助第三方软件工具验证如上理论知识:使用16进制编辑器打开某个GIF文件,我们可以清晰的看到文件头,是部分

截图16进制的 47 49 46 38 39 61所表示的正好是GIF89a。


有了如上理论知识,我们就可以很轻松的实现需求一了:

/**
 * 判断是否gif图片
 * @param inputStream
 * @return
 * @throws IOException
 */
private boolean isGif(InputStream inputStream) throws IOException {
    byte[] temp = new byte[3];
    int count = inputStream.read(temp);
    //可读字节数小于3
    if(count < 3) {
        temp = null;
        return false;
    }
    //满足下面的条件,说明是gif图
    if(temp[0] == (byte) 'G' && temp[1] == (byte) 'I' && temp[2] == (byte) 'F') {
        temp = null;
        return true;
    } else {
        temp = null;
        return false;
    }
}


5.需求二 & 逻辑屏幕标识符(Logical Screen Descript)

如上图,逻辑屏幕标识符配置了GIF图片一些全局属性,可以通过读取解析获取GIF图片的一些全局配置。我们以需求二为例:

/**
 * 获取gif图片宽高
 * @param file
 * @return
    */
public static int[] getGifFileWidthAndHeight(File file) {
   int[] result = new int[] { -1, -1 };
   if (file == null || !file.exists()) {
      return result;
   }
   try {
      InputStream inputStream = new FileInputStream(file);

      if (!isGif(inputStream)) {//判断是否gif
         return result;
      }

      inputStream.skip(3); //跳过中间3个

      int lenTemp = 4;// need content len
      int len = 2;// len for width and height , each occupy two byte .
      byte[] temp = new byte[lenTemp];
      byte[] width = new byte[len];
      byte[] height = new byte[len];
      inputStream.read(temp, 0, temp.length);

      width[0] = temp[0];
      width[1] = temp[1];
      result[0] = bytes2ToInt(width);

      height[0] = temp[2];
      height[1] = temp[3];
      result[1] = bytes2ToInt(height);
   } catch (FileNotFoundException e) {
      e.printStackTrace();
   } catch (IOException e) {
      e.printStackTrace();
   } catch (Exception e) {
      e.printStackTrace();
   }
   return result;
}
注意:宽高分别占用2个字节,且高位字节在后。


6.需求三 & 图形控制扩展(Graphic Control Extension)

89a版本,GIF添加了图形控制扩展块。放在一个图象块(图象标识符)的前面,用来控制紧跟在它后面的第一个图象的显示。


如上图:图形控制扩展块中包含了扩展块标识符、图形控制扩展标签、块大小、延迟时间等。可以通过读取解析获取GIF图片的

一些全局配置。我们以需求三获取和修改帧间隔为例:

/**
         * 处理帧间隔为0的gif图片
         * @param path 文件路径
         * @throws IOException
         */
    public static void dealGif(String path) {

        long start = 0;
        List<Integer> list = new ArrayList<>();
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(new File(path));

            if (!isGif(inputStream)) {
                return;
            }
            inputStream.skip(10);//跳过10个
            start = System.currentTimeMillis();
            for (int i = 13; ;) {//判断是否gif读取了3个+跳过了10个,所以这里从位置13开始

                int code = inputStream.read();
                i++;
                if (code == 0x21) {
                    code = inputStream.read();
                    i++;
                    if (code == 0xF9) {
                        code = inputStream.read();
                        i++;
                        if (code == 4) {
                            inputStream.skip(1);
                            int delay = readDelayTime(inputStream);
                            i += 3;
                            LogUtils.d(TAG, "path="+path);
                            LogUtils.d(TAG, "delay="+delay);
                            if (delay == 0) {

                                try {
                                    changeFile(path, i - 2, 1, 10);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                list.add(i - 2);
                            }
                        }
                    }

                } else if (code == -1) { //文件尾-结束
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        LogUtils.d(TAG, "dealGif time=" + (System.currentTimeMillis() - start) / 1000);
    }
/**
     * 修改gif图片固定位置值
     * @param fName
     * @param start
     * @param len
     * @param targetValue 目标值
     * @throws IOException
     */
    public static boolean changeFile(String fName, int start, int len, int targetValue) throws Exception{
        LogUtils.d(TAG, "path="+fName);
        //创建一个随机读写文件对象 ??
        java.io.RandomAccessFile raf = null;
        //打开一个文件通道 ??
        java.nio.channels.FileChannel channel = null;
        //映射文件中的某一部分数据以读写模式到内存中 ??
        java.nio.MappedByteBuffer buffer;
        try {
            raf = new java.io.RandomAccessFile(fName,"rw");
            channel = raf.getChannel();
            buffer = channel.map(FileChannel.MapMode.READ_WRITE, start, len);
            //示例修改字节 ??
            for(int i = 0; i < len; i++){
                byte src = buffer.get(i);
                LogUtils.d(TAG, "src="+String.valueOf(src));
                buffer.put(i, (byte) targetValue);
            }
            buffer.force();//制输出,在buffer中的改动生效到文件
            buffer.clear();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (channel != null) {
                channel.close();
            }
            if (raf != null) {
                raf.close();
            }
        }
        return true;
    }
/**
     * 读取帧间隔
     * @param inputStream
     * @return
     */
    private static int readDelayTime(InputStream inputStream) {
        byte[] bytes = new byte[2];
        try {
            inputStream.read(bytes, 0, bytes.length);
            return FileUtils.bytes2ToInt(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return -1;
    }
注意:如上方法通常是比较耗时的,根据具体的场景我们要有选择性的使用,或者可以放到服务端处理。

7.总结

以上就是学习GIF文件格式理论知识,在实际项目需求中的实际应用。更多的需求可以通过更多的学习和实践去尝试解决。

<think>在CocosCreator中,不支持直接导入GIF文件作为动画资源。但是我们可以通过将GIF分解为帧序列,然后使用SpriteFrame动画来实现类似GIF的效果。解决方案:1.将GIF文件分解成多个PNG或JPG图片(每一帧一张图片)。2.将这些图片导入到CocosCreator项目中。3.创建一个动画剪辑(AnimationClip),将这些图片按顺序设置为关键帧。4.使用Sprite组件播放这个动画剪辑。详细步骤:步骤1:分解GIF可以使用在线工具或软件(如Photoshop)将GIF分解为单帧图片,导出为PNG序列。步骤2:导入图片到CocosCreator将导出的帧图片放入项目的assets目录下。步骤3:创建动画剪辑-在资源管理器中,选中所有分解后的图片(按顺序选中)。-右键选择“创建动画剪辑”,这样会创建一个.anim文件。步骤4:创建节点并添加动画组件-在场景中创建一个空节点。-为这个节点添加一个Sprite组件(如果没有的话)。-再添加一个Animation组件。步骤5:将动画剪辑赋给Animation组件-将步骤3创建的.anim文件拖拽到Animation组件的Clips中。步骤6:播放动画-可以在编辑器中将Animation组件的PlayOnLoad勾选,这样就会自动播放。-也可以通过代码控制播放。代码控制示例:创建一个脚本,挂载到该节点上:```typescriptimport{_decorator,Component,Animation}from'cc';const{ccclass,property}=_decorator;@ccclass('GIFPlayer')exportclassGIFPlayerextendsComponent{privateanimation:Animation|null=null;onLoad(){//获取Animation组件this.animation=this.getComponent(Animation);}start(){if(this.animation){//播放默认动画剪辑this.animation.play();}}}```如果需要循环播放,可以在动画剪辑的属性中设置WrapMode为Loop。注意事项:-分解GIF得到的帧数可能会很多,注意性能问题。-如果GIF帧率很高,需要调整动画剪辑的采样率(sample)来匹配。另一种方案:使用第三方库解码GIF并实时渲染(不推荐,因为性能较差,且需要额外的工作量)由于CocosCreator本身不支持GIF,所以通常我们使用帧动画来模拟。但如果你确实需要动态加载GIF,可以考虑使用一个GIF解码库,然后在每帧中更新Sprite的SpriteFrame。但是这种方法在性能和内存上都不如预先分解的帧动画,尤其是在移动设备上。这里简单提一下动态加载GIF的思路(需要自己实现或寻找第三方库):1.使用一个JavaScript的GIF解码库(例如omggif)。2.将GIF文件作为二进制数据加载。3.解码GIF,获取每一帧的图像数据和延迟时间。4.创建多个Texture2D对象,并用解码出的图像数据填充。5.创建SpriteFrame数组,并按照延迟时间逐帧切换。由于这种方法比较复杂且性能开销大,这里不展开代码,除非有特殊需求,否则不建议使用。因此,对于大多数情况,推荐使用分解为帧序列的方法。相关问题:§§相关问题§§:1.在CocosCreator中如何优化帧动画的内存占用?2.CocosCreator的动画系统支持哪些事件回调?3.如何在CocosCreator中实现序列帧动画的播放暂停和继续?4.如何动态加载外部序列帧图片并创建动画?</think># Cocos Creator 导入与播放 GIF 动画的全面指南 在 Cocos Creator 中,由于引擎本身不直接支持 GIF 格式,我们需要将 GIF 转换为帧序列或精灵动画来实现类似效果。以下是几种高效实现 GIF 动画的方法: ## 方法一:将 GIF 转换为帧序列(推荐) ### 步骤 1: 将 GIF 分解为帧序列 使用工具将 GIF 分解为 PNG/JPG 帧序列: - Photoshop: 文件 → 导出 → 渲染视频 → 选择 PNG 序列 - 在线工具: ezgif.com/split - 命令行工具: `convert input.gif output_%04d.png` ### 步骤 2: 在 Cocos Creator 中导入帧序列 1. 将帧序列图片导入 assets 目录 2. 在资源管理器中全选所有帧 3. 右键选择 "创建精灵帧动画" ```typescript // 创建帧动画组件 import { _decorator, Component, Sprite, SpriteFrame, Animation, AnimationClip } from 'cc'; const { ccclass, property } = _decorator; @ccclass('FrameAnimationPlayer') export class FrameAnimationPlayer extends Component { @property([SpriteFrame]) frames: SpriteFrame[] = []; // 帧序列数组 @property frameRate: number = 12; // 帧率 (FPS) private sprite: Sprite = null!; private currentFrame: number = 0; private isPlaying: boolean = false; private accumulator: number = 0; onLoad() { this.sprite = this.getComponent(Sprite) || this.addComponent(Sprite); } start() { this.play(); } play() { this.isPlaying = true; this.currentFrame = 0; this.accumulator = 0; this.updateFrame(); } stop() { this.isPlaying = false; } pause() { this.isPlaying = false; } resume() { this.isPlaying = true; } update(dt: number) { if (!this.isPlaying || this.frames.length === 0) return; this.accumulator += dt; const frameTime = 1 / this.frameRate; while (this.accumulator >= frameTime) { this.accumulator -= frameTime; this.currentFrame = (this.currentFrame + 1) % this.frames.length; this.updateFrame(); } } private updateFrame() { this.sprite.spriteFrame = this.frames[this.currentFrame]; } } ``` ### 使用方法: 1. 将脚本挂载到节点 2. 在属性检查器中拖入帧序列 3. 设置帧率(默认12FPS) ## 方法二:使用 Animation 组件 ### 步骤 1: 创建动画剪辑 1. 在资源管理器中选择帧序列 2. 右键 → 创建 → Animation Clip 3. 命名为 `myGif.anim` ### 步骤 2: 创建动画控制器 ```typescript import { _decorator, Component, Animation } from 'cc'; const { ccclass } = _decorator; @ccclass('GifAnimationController') export class GifAnimationController extends Component { @property animationName: string = 'gif_animation'; // 动画剪辑名称 private animation: Animation = null!; onLoad() { this.animation = this.getComponent(Animation) || this.addComponent(Animation); this.animation.on(Animation.EventType.FINISHED, this.onAnimationFinished, this); } start() { this.playAnimation(); } playAnimation() { if (this.animation.getState(this.animationName)) { this.animation.play(this.animationName); } } stopAnimation() { this.animation.stop(); } setLoop(loop: boolean) { const state = this.animation.getState(this.animationName); if (state) { state.wrapMode = loop ? AnimationClip.WrapMode.Loop : AnimationClip.WrapMode.Normal; } } private onAnimationFinished() { console.log('Animation finished'); // 自定义结束逻辑 } } ``` ## 方法三:使用第三方库解码 GIF(高级) ### 安装 gif.js 库 ```bash npm install gif.js ``` ### GIF 解码与渲染 ```typescript import { _decorator, Component, Sprite, Texture2D, ImageAsset, gfx } from 'cc'; const { ccclass, property } = _decorator; import GIF from 'gif.js'; @ccclass('GifDecoder') export class GifDecoder extends Component { @property gifUrl: string = ''; // GIF 文件 URL private sprite: Sprite = null!; private frames: ImageAsset[] = []; private currentFrame: number = 0; private frameDelays: number[] = []; async onLoad() { this.sprite = this.getComponent(Sprite) || this.addComponent(Sprite); await this.loadAndDecodeGif(); this.playAnimation(); } private async loadAndDecodeGif(): Promise<void> { return new Promise((resolve, reject) => { const gifLoader = new GIF({ workerScript: 'gif.worker.js', // 需要提供 worker 文件 workers: 2, quality: 10, }); fetch(this.gifUrl) .then(response => response.arrayBuffer()) .then(buffer => { gifLoader.on('finished', (blob) => { this.processGIFResult(blob); resolve(); }); gifLoader.on('error', (err) => { console.error('GIF decoding error:', err); reject(err); }); gifLoader.on('progress', (p) => { console.log(`Decoding progress: ${p * 100}%`); }); gifLoader.addFrame(new Uint8Array(buffer)); gifLoader.render(); }); }); } private processGIFResult(blob: Blob) { const reader = new FileReader(); reader.onload = (event) => { const arrayBuffer = event.target?.result as ArrayBuffer; // 这里需要解析 GIF 结构获取帧数据 // 伪代码:实际实现需要解析 GIF 格式 this.extractFramesFromGIF(arrayBuffer); }; reader.readAsArrayBuffer(blob); } private extractFramesFromGIF(buffer: ArrayBuffer) { // 实际实现需要使用 GIF 解析库 // 这里简化处理,实际应解析出每帧图像和延迟时间 for (let i = 0; i < frameCount; i++) { const imageAsset = new ImageAsset(); imageAsset.reset(/* 图像数据 */); this.frames.push(imageAsset); this.frameDelays.push(delayTime); } } private playAnimation() { if (this.frames.length === 0) return; this.schedule(this.nextFrame, this.frameDelays[this.currentFrame] / 1000); } private nextFrame() { this.currentFrame = (this.currentFrame + 1) % this.frames.length; // 创建纹理 const texture = new Texture2D(); texture.image = this.frames[this.currentFrame]; // 更新精灵 this.sprite.spriteFrame = texture; // 安排下一帧 this.scheduleOnce( this.nextFrame, this.frameDelays[this.currentFrame] / 1000 ); } } ``` ## 方法四:使用图集动画(最佳性能) ### 步骤 1: 创建图集 1. 将 GIF 帧序列导入 Cocos Creator 2. 选择所有帧 → 右键 → 创建图集 3. 命名为 `gifAtlas` ### 步骤 2: 创建图集动画 ```typescript import { _decorator, Component, Sprite, SpriteAtlas, SpriteFrame } from 'cc'; const { ccclass, property } = _decorator; @ccclass('AtlasAnimationPlayer') export class AtlasAnimationPlayer extends Component { @property(SpriteAtlas) atlas: SpriteAtlas = null!; // 图集资源 @property frameRate: number = 12; // 帧率 @property loop: boolean = true; // 是否循环 private sprite: Sprite = null!; private frames: SpriteFrame[] = []; private currentFrame: number = 0; private accumulator: number = 0; onLoad() { this.sprite = this.getComponent(Sprite) || this.addComponent(Sprite); // 从图集获取所有帧 if (this.atlas) { this.frames = this.atlas.getSpriteFrames(); } } start() { this.play(); } play() { this.currentFrame = 0; this.accumulator = 0; this.updateFrame(); } update(dt: number) { if (this.frames.length === 0) return; this.accumulator += dt; const frameTime = 1 / this.frameRate; if (this.accumulator >= frameTime) { this.accumulator = 0; this.currentFrame++; if (this.currentFrame >= this.frames.length) { if (this.loop) { this.currentFrame = 0; } else { this.currentFrame = this.frames.length - 1; return; } } this.updateFrame(); } } private updateFrame() { this.sprite.spriteFrame = this.frames[this.currentFrame]; } } ``` ## 性能优化技巧 1. **内存管理**: - 使用图集减少 draw call - 及时销毁不再使用的纹理 - 使用压缩纹理格式 (ASTC, PVRTC) 2. **帧率控制**: ```typescript // 根据设备性能动态调整帧率 adjustFrameRateBasedOnPerformance() { if (sys.platform === sys.Platform.MOBILE_BROWSER) { this.frameRate = 10; // 移动设备使用较低帧率 } else { this.frameRate = 15; // PC使用较高帧率 } } ``` 3. **按需加载**: ```typescript // 动态加载图集 async loadAtlasDynamic(path: string) { await new Promise((resolve, reject) => { resources.load(path, SpriteAtlas, (err, atlas) => { if (err) return reject(err); this.atlas = atlas; this.frames = atlas.getSpriteFrames(); resolve(); }); }); } ``` ## 各种方法对比 | 方法 | 优点 | 缺点 | 适用场景 | |------|------|------|---------| | 帧序列 | 简单直观,易于实现 | 内存占用高,文件数量多 | 小型 GIF,简单动画 | | Animation 组件 | 编辑器支持好,功能完善 | 需要创建额外资源,学习曲线 | 复杂动画,需要编辑器控制 | | 第三方解码 | 直接使用 GIF 文件 | 性能差,实现复杂,兼容性问题 | 需要动态加载外部 GIF | | 图集动画 | 性能最佳,内存占用低 | 需要预处理 | 性能敏感场景,移动设备 | ## 最佳实践建议 1. **小型静态 GIF**: - 使用帧序列方法 - 控制在 20 帧以内 - 使用 PNG-8 格式减少体积 2. **复杂动画**: - 使用 Animation 组件 - 添加事件回调 - 使用曲线编辑器调整 3. **动态加载 GIF**: - 使用图集预加载 - 按需加载不同分辨率 - 添加加载进度指示 4. **性能优化**: - 使用图集减少 draw call - 限制同时播放的动画数量 - 使用对象池复用动画节点
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值