判断GIF类型并使用ImageDecoder解析GIF图

一、判断是否为GIF图片类型

在JavaScript中,判断用户上传的文件是否为GIF文件类型时,通常可以通过检查文件的type属性或文件的拓展名来判断,但是由于文件拓展名可以轻易被用户修改,type属性是由浏览器根据文件拓展名猜测得出的,因此这种判断方式并不总是准确的。

为了更准确的判断文件类型,需要读取文件的头部字节,并检查这些字节是否符合GIF文件的规范。

要检查文件头部字节以确定文件是否为GIF格式,可以使用JavaScript的FileReader API来读取文件的前几个字节,并与GIF文件的魔数(Magic Number)进行比较。GIF文件的魔数是GIF87a或GIF89a,它们位于文件的前几个字节中。

// 文件输入元素
const fileInput = document.getElementById('file-input')

// 监听文件变化事件
fileInput.addEventListener('change', async fucntion(e) {
    // 获取用户选择的文件
    const file = e.target.files[0]

    if(file) {
        const isGif = await checkGifFileType(file)
        if(isGif) {
            // 是gif
        } else {
            // 不是gif
        }
    }
})
/**
 * 检查文件类型是否是gif
 * 
 * @param {*} file 
 * @returns 
 */
export function checkGifFileType(file) {
	// 创建一个FileReader对象
	const reader = new FileReader();

	// 读取文件的前几个字节
	reader.readAsArrayBuffer(file.slice(0, 6)); // GIF的魔数只需要6个字节

	return new Promise((resolve, reject) => {
		reader.onload = function (e) {
			// 将ArrayBuffer转换为Uint8Array以便读取字节
			const arrayBuffer = e.target.result;
			const uint8Array = new Uint8Array(arrayBuffer);

			// GIF文件的魔数可以是'GIF87a'或'GIF89a',转换为ASCII码分别为[71, 73, 70, 56, 55, 97]或[71, 73, 70, 56, 57, 97]
			// 检查文件的前6个字节是否匹配GIF的魔数
			const gif87a = [71, 73, 70, 56, 55, 97];
			const gif89a = [71, 73, 70, 56, 57, 97];

			if (
				(uint8Array[0] === gif87a[0] &&
					uint8Array[1] === gif87a[1] &&
					uint8Array[2] === gif87a[2] &&
					uint8Array[3] === gif87a[3] &&
					uint8Array[4] === gif87a[4] &&
					uint8Array[5] === gif87a[5]) ||
				(uint8Array[0] === gif89a[0] &&
					uint8Array[1] === gif89a[1] &&
					uint8Array[2] === gif89a[2] &&
					uint8Array[3] === gif89a[3] &&
					uint8Array[4] === gif89a[4] &&
					uint8Array[5] === gif89a[5])
			) {
				resolve(true); // 是GIF文件
			} else {
				resolve(false); // 不是GIF文件
			}
		};

		reader.onerror = function (error) {
			reject(error);
		};
	});
}

二、解析GIF,并在canvas上播放

GIF本质上和视频一样,都是一帧一帧的图片拼合而成,所以,在canvas上播放GIF功能实现的要点,就是获取具体某一帧的资源。

  1. 使用ImageDecoder API解析GIF每一帧的图像资源;
  2. 将该图像资源绘制在canvas画布上;

注意:目前ImageDecoder仅Chrome浏览器支持,如果考虑兼容性,可以使用libgif.js等第三方库去解析GIF。

1、资源获取

使用fetch方法获取GIF图片资源,注意跨域问题。

fetch("xxx.gif").then((response) => {
    // response.body 就是图像资源数据
});

2、使用ImageDecoder解析

imageDecoder对象就包含了一系列的属性和方法,用来对解析好的图像数据进行各种各样的处理。

const imageDecoder = new ImageDecoder({ 
    data: response.body, 
    type: "image/gif" 
});

获取GIF第一帧的图形数据,则可以:

imageDecoder.decode({ 
    frameIndex: 0
}).then((result) => {
    // result 对象就是解析后的结果
});

result 对象包括下面这些属性,其中result.image 的返回值是一个 VideoFrame 对象,包含很多属性和方法,例如,帧图像的编码尺寸,显示尺寸,时间戳,时间间隔等,可以作为 ImageSource 绘制在 canvas 画布上。

{
    // 解码的图像
    image: VideoFrame,
    // 如果为true,则表示该图像包含最终的完整细节输出。
    complete: boolean
}

result.image.timestamp:当前帧出现的时间戳,单位为微分秒,即万分之一秒

result.image.duration:当前帧持续的时长,单位为微分秒,即万分之一秒

const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d");

context.drawImage(result.image, 0, 0);

3、简单封装

export function giftDecoder(url) {
	return new Promise((resolve, reject) => {
		fetch(url).then(async (response) => {
			// response.body 就是图像资源数据
			const imageDecoder = new ImageDecoder({ 
				data: response.body, 
				type: "image/gif" 
			});
			let _d = await imageDecoder.decode({ frameIndex: 0 })
			console.log(imageDecoder, _d)

			const track = imageDecoder.tracks.selectedTrack;
			console.log(track)
			let arr = []
			let totalTime = 0
			for(let i = 0; i < track.frameCount; i++) {
				let result = await imageDecoder.decode({ 
					frameIndex: i
				})

				if(result) {
					// result 对象就是解析后的结果
					// 1000000
					// timestamp:当前帧出现的时间戳,单位为微分秒
					// duration:当前帧持续的时长,单位为微分秒
					arr.push(result)
					if(i == track.frameCount - 1) {
						totalTime = result.image.timestamp + result.image.duration
					}
				} else {
					reject()
					break
				}
				
			}
			console.error('gif数组', arr)

			resolve({
				totalTime,
				list: arr
			})
		});
	})
}
// gif图特殊处理
const gifData = await giftDecoder(gifUrl)
             
console.error('gif图特殊处理', gifData)
              

三、使用 gifuct-js 库解析gif

gifuct-js是由Matt Way开发的一个轻量级JavaScript库,专门用于处理和创建GIF动图。它提供了强大的API,让开发者能够轻松地解码、编码、操作及优化GIF文件,适用于网页应用或任何需要在前端处理GIF的场景。

项目地址:https://gitcode.com/matt-way/gifuct-js

技术分析

  • 解码与编码能力
  • Gifuct-js的核心是其高效的GIF解码器和编码器。通过原生JavaScript实现,它能够快速解析GIF文件的逻辑屏幕描述、图像描述、图形控制扩展等信息,同时也能生成符合标准的新GIF文件。
  • 图像操作接口
  • 该项目提供了丰富的API,支持对帧进行添加、删除、重排、调整透明度等操作。例如,你可以通过addFrame方法将新的帧添加到GIF中,或者通过removeFrame方法移除特定帧,以实现动态效果的定制。
  • 性能优化
  • 考虑到前端性能,Gifuct-js设计时就注重了内存管理和运行效率。它采用流式处理,减少了不必要的数据复制,从而降低内存占用并提升处理速度。
  • 兼容性
  • Gifuct-js基于WebAssembly和JavaScript,使其在现代浏览器中具有良好的兼容性。对于不支持WebAssembly的老版本浏览器,项目还提供了一个纯JavaScript的回退方案。

 

1、安装

npm install gifuct-js

2、解码

此解码器使用**js-binary-schema-parser**解析 GIF 文件。这意味着要解码 GIF 文件,首先需要将其转换为 Uint8Array 缓冲区。

fetch

import { parseGIF, decompressFrames } from 'gifuct-js';

var promisedGif = fetch(gifURL)
    .then(resp => resp.arrayBuffer())
    .then(buff => {
        var gif = parseGIF(buff);
        var frames = decompressFrames(gif, true);
        return gif;
    });

XMLHttpRequest

import { parseGIF, decompressFrames } from 'gifuct-js';

var oReq = new XMLHttpRequest();
oReq.open("GET", gifURL, true);
oReq.responseType = "arraybuffer";

oReq.onload = function (oEvent) {
    var arrayBuffer = oReq.response; // 注意:不是 oReq.responseText
    if (arrayBuffer) {
        var gif = parseGIF(arrayBuffer);
        var frames = decompressFrames(gif, true);
        // 处理帧数据
    }
};

oReq.send(null);

结果

decompressFrames(gif, buildPatch) 函数返回一个包含所有 GIF 图像帧及其元数据的数组。

{
    // 每个像素的调色板索引
    pixels: [...],
    // GIF 帧的尺寸(见处置方法)
    dims: {
        top: 0,
        left: 10,
        width: 100,
        height: 50
    },
    // 此帧应显示的毫秒数
    delay: 50,
    // 处置方法(见下文)
    disposalType: 1,
    // 指向像素数据的颜色数组
    colorTable: [...],
    // 可选的代表透明度的色彩索引(见下文)
    transparentIndex: 33,
    // 绘制准备好的 Uint8ClampedArray 颜色补丁信息
    patch: [...]
}
自动补丁生成:

如果 dcompressFrames() 函数的 buildPatch 参数为 true,解析器不仅会返回解析和解压缩的 GIF 帧,还会为每个 GIF 帧图像创建可直接用于画布的 Uint8ClampedArray 数组,以便使用 ctx.putImageData() 等方式轻松绘制。这是常见需求,但由于它涉及到透明度假设,所以设为可选项。

处置方法:

像素数据是以每个像素的索引列表存储的。这些索引指向 colorTable 数组中的值,表示每个像素应绘制的颜色。GIF 的每一帧可能不是全尺寸,而是一个需要在特定位置绘制的补丁。disposalType 定义了如何在 GIF 画布上绘制该补丁。大多数情况下,该值为 1,表示 GIF 帧应简单地覆盖现有的 GIF 画布,而不改变补丁尺寸之外的任何像素。

透明性:

如果一帧定义了 transparentIndex,则意味着像素数据中与该索引匹配的任何像素不应被绘制。在使用画布绘图时,这表示将此像素的 alpha 值设置为 0

3、封装

import { parseGIF, decompressFrames } from 'gifuct-js'

export function giftDecoder(url) {
	return new Promise((resolve, reject) => {

		let arr = []
		let totalTime = 0

		if('ImageDecoder' in window) {
			fetch(url).then(async (response) => {
				// response.body 就是图像资源数据
				let arr = []
				let totalTime = 0
	
				const imageDecoder = new ImageDecoder({ 
					data: response.body, 
					type: "image/gif" 
				});
				let _d = await imageDecoder.decode({ frameIndex: 0 })
				console.log(imageDecoder, _d)
	
				const track = imageDecoder.tracks.selectedTrack;
				console.log(track)
				
				for(let i = 0; i < track.frameCount; i++) {
					let result = await imageDecoder.decode({ 
						frameIndex: i
					})
	
					if(result) {
						// result 对象就是解析后的结果
						// 1000000
						// timestamp:当前帧出现的时间戳,单位为微分秒
						// duration:当前帧持续的时长,单位为微分秒
						arr.push(result)
						if(i == track.frameCount - 1) {
							totalTime = result.image.timestamp + result.image.duration
						}
					} else {
						reject()
						break
					}
					
				}
				console.error('gif数组', arr, response)
	
				resolve({
					totalTime:totalTime/1000000 ,
					list: arr
				})
			});
		} else {

			let oReq = new XMLHttpRequest();
			oReq.open("GET", url, true);
			oReq.responseType = "arraybuffer";
	
			oReq.onload = async function (oEvent) {
				let arrayBuffer = oReq.response; // 注意:不是 oReq.responseText
				if (arrayBuffer) {
					let gif = parseGIF(arrayBuffer);
					let frames = decompressFrames(gif, true);
					// 处理帧数据
					let accumulatedTime = 0

					const _canvas = document.createElement('canvas')
					const _ctx = _canvas.getContext('2d')
					_canvas.width = gif.lsd.width
					_canvas.height = gif.lsd.height

					for(let i = 0; i < frames.length; i++) {
						let frame = frames[i]
						// _ctx.clearRect(0, 0, _canvas.width, _canvas.height)

						let imageData = _ctx.createImageData(frame.dims.width, frame.dims.height)
						imageData.data.set(frame.patch)
						_ctx.putImageData(imageData, frame.dims.left, frame.dims.top)
						let _blob = await canvasToBlob(_canvas, 'image/png')
						let _url = URL.createObjectURL(_blob)

						const img = new Image()
						img.src = _url
						await imgOnload(img)

						totalTime += frame.delay 
						arr.push({
							timestamp: accumulatedTime,
							duration: frame.delay ,
							img: img
						})

						accumulatedTime += frame.delay 
					}

					resolve({
						totalTime: totalTime/1000,
						list: arr
					})
					// console.error('xxx', totalTime, arr)
				} else {
					reject()
				}
			};
	
			oReq.send(null);
		}

		
	})
}

function canvasToBlob(canvas, type, quality) {
	return new Promise(resolve => {
		canvas.toBlob((blob) => {
			resolve(blob)
		}, type, quality)
	})
}

function imgOnload(img) {
	return new Promise(resolve => {
		img.onload = function() {
			resolve()
		}
	})
}

参考文档

https://developer.mozilla.org/en-US/docs/Web/API/VideoFrame

https://developer.mozilla.org/en-US/docs/Web/API/ImageDecoder

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
package org.hds.Graphics; import java.net.*; import java.io.*; import java.util.*; import java.awt.*; import java.awt.image.*; public class GifDecoder { /** * File read status: No errors. */ public static final int STATUS_OK = 0; /** * File read status: Error decoding file (may be partially decoded) */ public static final int STATUS_FORMAT_ERROR = 1; /** * File read status: Unable to open source. */ public static final int STATUS_OPEN_ERROR = 2; protected BufferedInputStream in; protected int status; protected int width; // full image width protected int height; // full image height protected boolean gctFlag; // global color table used protected int gctSize; // size of global color table protected int loopCount = 1; // iterations; 0 = repeat forever protected int[] gct; // global color table protected int[] lct; // local color table protected int[] act; // active color table protected int bgIndex; // background color index protected int bgColor; // background color protected int lastBgColor; // previous bg color protected int pixelAspect; // pixel aspect ratio protected boolean lctFlag; // local color table flag protected boolean interlace; // interlace flag protected int lctSize; // local color table size protected int ix, iy, iw, ih; // current image rectangle protected Rectangle lastRect; // last image rect protected BufferedImage image; // current frame protected BufferedImage lastImage; // previous frame protected byte[] block = new byte[256]; // current data block protected int blockSize = 0; // block size // last graphic control extension info protected int dispose = 0; // 0=no action; 1=leave in place; 2=restore to bg; 3=restore to prev protected int lastDispose = 0; protected boolean transparency = false; // use transparent color protected int delay = 0; // delay in milliseconds protected int totaldelay = 0; // delay in milliseconds protected int transIndex; // transparent color index protected static final int MaxStackSize = 4096; // max decoder pixel stack size // LZW decoder working arrays protected short[] prefix; protected byte[] suffix; protected byte[] pixelStack; protected byte[] pixels; protected ArrayList frames; // frames read from current file protected int frameCount; static class GifFrame { public GifFrame(BufferedImage im, int del) { image = im; delay = del; } public BufferedImage image; public int delay; } /** * Gets display duration for specified frame. * * @param n int index of frame * @return delay in milliseconds */ public int getDelay(int n) { // delay = -1; if ((n >= 0) && (n < frameCount)) { delay = ((GifFrame) frames.get(n)).delay; } return delay; } /** * Gets the number of frames read from file. * @return frame count */ public int getFrameCount() { return frameCount; } /** * Gets the number of frames read from file. * @return frame count */ public int gettotaldelay() { return totaldelay; } /** * Gets the first (or only) image read. * * @return BufferedImage containing first frame, or null if none. */ public BufferedImage getImage() { return getFrame(0); } /** * Gets the "Netscape" iteration count, if any. * A count of 0 means repeat indefinitiely. * * @return iteration count if one was specified, else 1. */ public int getLoopCount() { return loopCount; } /** * Creates new frame image from current data (and previous * frames as specified by their disposition codes). */ protected void setPixels() { // expose destination image's pixels as int array int[] dest = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); // fill in starting image contents based on last image's dispose code if (lastDispose > 0) { if (lastDispose == 3) { // use image before last int n = frameCount - 2; if (n > 0) { lastImage = getFrame(n - 1); } else { lastImage = null; } } if (lastImage != null) { int[] prev = ((DataBufferInt) lastImage.getRaster().getDataBuffer()).getData(); System.arraycopy(prev, 0, dest, 0, width * height); // copy pixels if (lastDispose == 2) { // fill last image rect area with background color Graphics2D g = image.createGraphics(); Color c = null; if (transparency) { c = new Color(0, 0, 0, 0); // assume background is transparent } else { c = new Color(lastBgColor); // use given background color } g.setColor(c); g.setComposite(AlphaComposite.Src); // replace area g.fill(lastRect); g.dispose(); } } } // copy each source line to the appropriate place in the destination int pass = 1; int inc = 8; int iline = 0; for (int i = 0; i < ih; i++) { int line = i; if (interlace) { if (iline >= ih) { pass++; switch (pass) { case 2 : iline = 4; break; case 3 : iline = 2; inc = 4; break; case 4 : iline = 1; inc = 2; } } line = iline; iline += inc; } line += iy; if (line < height) { int k = line * width; int dx = k + ix; // start of line in dest int dlim = dx + iw; // end of dest line if ((k + width) < dlim) { dlim = k + width; // past dest edge } int sx = i * iw; // start of line in source while (dx < dlim) { // map color and insert in destination int index = ((int) pixels[sx++]) & 0xff; int c = act[index]; if (c != 0) { dest[dx] = c; } dx++; } } } } /** * Gets the image contents of frame n. * * @return BufferedImage representation of frame, or null if n is invalid. */ public BufferedImage getFrame(int n) { BufferedImage im = null; if ((n >= 0) && (n < frameCount)) { im = ((GifFrame) frames.get(n)).image; } return im; } /** * Gets image size. * * @return GIF image dimensions */ public Dimension getFrameSize() { return new Dimension(width, height); } /** * Reads GIF image from stream * * @param BufferedInputStream containing GIF file. * @return read status code (0 = no errors) */ public int read(BufferedInputStream is) { init(); if (is != null) { in = is; readHeader(); if (!err()) { readContents(); if (frameCount < 0) { status = STATUS_FORMAT_ERROR; } } } else { status = STATUS_OPEN_ERROR; } try { is.close(); } catch (IOException e) { } return status; } /** * Reads GIF image from stream * * @param InputStream containing GIF file. * @return read status code (0 = no errors) */ public int read(InputStream is) { init(); if (is != null) { if (!(is instanceof BufferedInputStream)) is = new BufferedInputStream(is); in = (BufferedInputStream) is; readHeader(); if (!err()) { readContents(); if (frameCount < 0) { status = STATUS_FORMAT_ERROR; } } } else { status = STATUS_OPEN_ERROR; } try { is.close(); } catch (IOException e) { } return status; } /** * Reads GIF file from specified file/URL source * (URL assumed if name contains ":/" or "file:") * * @param name String containing source * @return read status code (0 = no errors) */ public int read(String name) { status = STATUS_OK; try { name = name.trim().toLowerCase(); if ((name.indexOf("file:") >= 0) || (name.indexOf(":/") > 0)) { URL url = new URL(name); in = new BufferedInputStream(url.openStream()); } else { in = new BufferedInputStream(new FileInputStream(name)); } status = read(in); } catch (IOException e) { status = STATUS_OPEN_ERROR; } return status; } /** * Decodes LZW image data into pixel array. * Adapted from John Cristy's ImageMagick. */ protected void decodeImageData() { int NullCode = -1; int npix = iw * ih; int available, clear, code_mask, code_size, end_of_information, in_code, old_code, bits, code, count, i, datum, data_size, first, top, bi, pi; if ((pixels == null) || (pixels.length < npix)) { pixels = new byte[npix]; // allocate new pixel array } if (prefix == null) prefix = new short[MaxStackSize]; if (suffix == null) suffix = new byte[MaxStackSize]; if (pixelStack == null) pixelStack = new byte[MaxStackSize + 1]; // Initialize GIF data stream decoder. data_size = read(); clear = 1 << data_size; end_of_information = clear + 1; available = clear + 2; old_code = NullCode; code_size = data_size + 1; code_mask = (1 << code_size) - 1; for (code = 0; code < clear; code++) { prefix[code] = 0; suffix[code] = (byte) code; } // Decode GIF pixel stream. datum = bits = count = first = top = pi = bi = 0; for (i = 0; i < npix;) { if (top == 0) { if (bits < code_size) { // Load bytes until there are enough bits for a code. if (count == 0) { // Read a new data block. count = readBlock(); if (count <= 0) break; bi = 0; } datum += (((int) block[bi]) & 0xff) << bits; bits += 8; bi++; count--; continue; } // Get the next code. code = datum & code_mask; datum >>= code_size; bits -= code_size; // Interpret the code if ((code > available) || (code == end_of_information)) break; if (code == clear) { // Reset decoder. code_size = data_size + 1; code_mask = (1 << code_size) - 1; available = clear + 2; old_code = NullCode; continue; } if (old_code == NullCode) { pixelStack[top++] = suffix[code]; old_code = code; first = code; continue; } in_code = code; if (code == available) { pixelStack[top++] = (byte) first; code = old_code; } while (code > clear) { pixelStack[top++] = suffix[code]; code = prefix[code]; } first = ((int) suffix[code]) & 0xff; // Add a new string to the string table, if (available >= MaxStackSize) break; pixelStack[top++] = (byte) first; prefix[available] = (short) old_code; suffix[available] = (byte) first; available++; if (((available & code_mask) == 0) && (available < MaxStackSize)) { code_size++; code_mask += available; } old_code = in_code; } // Pop a pixel off the pixel stack. top--; pixels[pi++] = pixelStack[top]; i++; } for (i = pi; i < npix; i++) { pixels[i] = 0; // clear missing pixels } } /** * Returns true if an error was encountered during reading/decoding */ protected boolean err() { return status != STATUS_OK; } /** * Initializes or re-initializes reader */ protected void init() { status = STATUS_OK; frameCount = 0; frames = new ArrayList(); gct = null; lct = null; } /** * Reads a single byte from the input stream. */ protected int read() { int curByte = 0; try { curByte = in.read(); } catch (IOException e) { status = STATUS_FORMAT_ERROR; } return curByte; } /** * Reads next variable length block from input. * * @return number of bytes stored in "buffer" */ protected int readBlock() { blockSize = read(); int n = 0; if (blockSize > 0) { try { int count = 0; while (n < blockSize) { count = in.read(block, n, blockSize - n); if (count == -1) break; n += count; } } catch (IOException e) { } if (n < blockSize) { status = STATUS_FORMAT_ERROR; } } return n; } /** * 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) */ protected int[] readColorTable(int ncolors) { int nbytes = 3 * ncolors; int[] tab = null; byte[] c = new byte[nbytes]; int n = 0; try { n = in.read(c); } catch (IOException e) { } if (n < nbytes) { status = STATUS_FORMAT_ERROR; } else { tab = new int[256]; // max size to avoid bounds checks int i = 0; int j = 0; while (i < ncolors) { int r = ((int) c[j++]) & 0xff; int g = ((int) c[j++]) & 0xff; int b = ((int) c[j++]) & 0xff; tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b; } } return tab; } /** * Main file parser. Reads GIF content blocks. */ protected void readContents() { // read GIF file content blocks boolean done = false; while (!(done || err())) { int code = read(); switch (code) { case 0x2C : // image separator readImage(); break; case 0x21 : // extension code = read(); switch (code) { case 0xf9 : // graphics control extension readGraphicControlExt(); break; case 0xff : // application extension readBlock(); String app = ""; for (int i = 0; i < 11; i++) { app += (char) block[i]; } if (app.equals("NETSCAPE2.0")) { readNetscapeExt(); } else skip(); // don't care break; default : // uninteresting extension skip(); } break; case 0x3b : // terminator done = true; break; case 0x00 : // bad byte, but keep going and see what happens break; default : status = STATUS_FORMAT_ERROR; } } } /** * Reads Graphics Control Extension values */ protected void readGraphicControlExt() { read(); // block size int packed = read(); // packed fields dispose = (packed & 0x1c) >> 2; // disposal method if (dispose == 0) { dispose = 1; // elect to keep old image if discretionary } transparency = (packed & 1) != 0; delay = readShort() * 10; // delay in milliseconds transIndex = read(); // transparent color index read(); // block terminator } /** * Reads GIF file header information. */ protected void readHeader() { String id = ""; for (int i = 0; i < 6; i++) { id += (char) read(); } /* * 如果id!=GIF89a佳毅判断不了暂时不用 */ if(!id.equals("GIF89a")) { status = STATUS_FORMAT_ERROR; return; } if (!id.startsWith("GIF")) { status = STATUS_FORMAT_ERROR; return; } readLSD(); if (gctFlag && !err()) {//全局定义颜色列表 gct = readColorTable(gctSize); bgColor = gct[bgIndex]; } } /** * Reads next frame image * 读每帧片信息 */ protected void readImage() { ix = readShort(); // (sub)image position & size iy = readShort(); iw = readShort(); ih = readShort(); if(ix > width || iy > height || iw > width || ih > height)//当帧位置大小有问题佳毅不支持 {status = STATUS_FORMAT_ERROR;} int packed = read(); lctFlag = (packed & 0x80) != 0; // 1 - local color table flag局部颜色列表 interlace = (packed & 0x40) != 0; // 2 - interlace flag // 3 - sort flag // 4-5 - reserved lctSize = 2 << (packed & 7); // 6-8 - local color table size if (lctFlag) { status = STATUS_FORMAT_ERROR;//局部颜色列表 佳毅不支持 lct = readColorTable(lctSize); // read table act = lct; // make local table active } else { act = gct; // make global table active if (bgIndex == transIndex) bgColor = 0; } int save = 0; if (transparency) { save = act[transIndex]; act[transIndex] = 0; // set transparent color if specified } if (act == null) { status = STATUS_FORMAT_ERROR; // no color table defined } if (err()) return; decodeImageData(); // decode pixel data skip(); if (err()) return; frameCount++; // create new image to receive frame data image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE); setPixels(); // transfer pixel data to image frames.add(new GifFrame(image, delay)); // add image to frame list totaldelay += delay; if (transparency) { act[transIndex] = save; } resetFrame(); } /** * Reads Logical Screen Descriptor */ protected void readLSD() { // logical screen size width = readShort(); height = readShort(); // packed fields int packed = read(); gctFlag = (packed & 0x80) != 0; // 1 : global color table flag 全局定义颜色列表 true // 2-4 : color resolution // 5 : gct sort flag gctSize = 2 << (packed & 7); // 6-8 : gct size bgIndex = read(); // background color index pixelAspect = read(); // pixel aspect ratio } /** * Reads Netscape extenstion to obtain iteration count */ protected void readNetscapeExt() { do { readBlock(); if (block[0] == 1) { // loop count sub-block int b1 = ((int) block[1]) & 0xff; int b2 = ((int) block[2]) & 0xff; loopCount = (b2 << 8) | b1; } } while ((blockSize > 0) && !err()); } /** * Reads next 16-bit value, LSB first */ protected int readShort() { // read 16-bit value, LSB first return read() | (read() << 8); } /** * Resets frame state for reading next image. */ protected void resetFrame() { lastDispose = dispose; lastRect = new Rectangle(ix, iy, iw, ih); lastImage = image; lastBgColor = bgColor; int dispose = 0; boolean transparency = false; int delay = 0; lct = null; } protected void skip() { do { readBlock(); } while ((blockSize > 0) && !err()); } }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值