GIF解码和编码操作库源码_第1页
GIF解码和编码操作库源码_第2页
GIF解码和编码操作库源码_第3页
GIF解码和编码操作库源码_第4页
GIF解码和编码操作库源码_第5页
已阅读5页,还剩47页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

GIF 解码和编码操作库源码 2007 01 10 16 52 GIF 解码和编码操作库源码 共有四个类文件 请下载 1 AnimatedGifEncoder java 2 GifDecoder java 3 LZWEncoder java 4 NeuQuant java 简单应用 import javax imageio ImageIO import java io import java awt image public class Testgif public static void main String args try BufferedImage src ImageIO read new File c work 1 jpg 读入文件 BufferedImage src1 ImageIO read new File c work 2 jpg 读入文件 BufferedImage src2 ImageIO read new File c work 3 jpg 读入文件 AnimatedGifEncoder e new AnimatedGifEncoder e setRepeat 0 e start c work laoma gif e setDelay 3000 1 frame per sec e addFrame src e setDelay 1000 e addFrame src1 e setDelay 100 e addFrame src2 e finish catch IOException e e printStackTrace 下面的例子来自 作者 ideas 1 多张 jpg 图合成 gif 动画 把多张 jpg 图片合成一张 param pic String 多个 jpg 文件名 包含路径 param newPic String 生成的 gif 文件名 包含路径 private synchronized void jpgToGif String pic String newPic try AnimatedGifEncoder e new AnimatedGifEncoder e setRepeat 0 e start newPic BufferedImage src new BufferedImage pic length for int i 0 i src length i e setDelay 200 设置播放的延迟时间 src i ImageIO read new File pic i 读入需要 播放的 jpg 文件 e addFrame src i 添加到帧中 e finish catch Exception e System out println jpgToGif Failed e printStackTrace 2 gif 动画分解成多张 jpg 把 gif 图片按帧拆分成 jpg 图片 param gifName String 小 gif 图片 路径 名称 param path String 生成小 jpg 图片的路径 return String 返回生成小 jpg 图片的名称 private synchronized String splitGif String gifName String path try GifDecoder decoder new GifDecoder decoder read gifName int n decoder getFrameCount 得到 frame 的个数 String subPic new String n String tag this getTag for int i 0 i n i BufferedImage frame decoder getFrame i 得到帧 int delay decoder getDelay i 得到延迟时间 生成小的 JPG 文件 subPic i path String value i jpg FileOutputStream out new FileOutputStream subPic i ImageIO write frame jpeg out JPEGImageEncoder encoder JPEGCodec createJPEGEncode r out encoder encode frame 存盘 out flush out close return subPic catch Exception e System out println splitGif Failed e printStackTrace return null 3 根据提供的文字生成 jpg 图片 根据提供的文字生成 jpg 图片 param s String 文字 param smallWidth int 每个字的宽度和高度是一样的 param bgcolor Color 背景色 param fontcolor Color 字色 param fontPath String 字体文件 param jpgname String jpg 图片名 return private String createJpgByFont String s int smallWidth Color bgc olor Color fontcolor String fontPath String jpgname try BufferedImage bimage new BufferedImage s length small Width smallWidth B ufferedImage TYPE INT RGB Graphics2D g bimage createGraphics g setColor bgcolor 背景色 g fillRect 0 0 smallWidth smallWidth 画一个矩形 去除锯齿 当设置的字体过大的时候 会出现锯齿 g setRenderingHint RenderingHints KEY ANTIALIASING Render ingHints VALUE ANTIALIAS ON g setColor fontcolor 字的颜色 File file new File fontPath 字体文件 根据字体文件所在位置 创建新的字体对象 此语句在 jdk1 5 下 面才支持 Font font Font createFont Font TRUETYPE FONT file font deriveFont float f 复制当前 Font 对象并应用新设置字 体的大小 g setFont font deriveFont float smallWidth g drawString s 0 smallWidth 在指定坐标除添加文字 g dispose FileOutputStream out new FileOutputStream jpgname 指定输出文件 JPEGImageEncoder encoder JPEGCodec createJPEGEncoder ou t JPEGEncodeParam param encoder getDefaultJPEGEncodeParam bimage param setQuality 50f true encoder encode bimage param 存盘 out flush out close catch Exception e System out println createJpgByFont Failed e printStackTrace 4 多张小 jpg 图合成一张大 JPG 图 在这里对大图只作宽度限制 不做高度限 制 将多个小图片合成一张大 jpg 图 小的 jpg 图片按照行列顺序平铺 param smallJPG ArrayList 一组小的 jpg 图片 param bigWidth int 大图宽度 param smallWidth int 单个文字生成的小图的宽度和高度是一致的 return private void createBigJPG ArrayList smallJPG int bigWidth int smallHeigh Color bgColor String picName try if bigWidth smallWidth 如果大图片的高度比小图片的高 度还小 直接返回 return int colCount bigWidth smallWidth 每行放置的字数 int leftMargin int bigWidth colCount smallWidth 2f 左边距 int rowCount smallJPG size 小图行数 int setWidth bigWidth 每列中间不留空隙 只留左右边距 int setHeight smallWidth rowCount 按照大图片宽高绘制一个背景图片 BufferedImage bufImage new BufferedImage setWidth setH eight BufferedImage TYPE INT RGB Graphics2D g bufImage createGraphics g setColor bgColor 背景的颜色 g fillRect 0 0 setWidth setHeight int y 0 纵坐标 for int i 0 i rowCount i 遍历每行 ArrayList col ArrayList smallJPG get i int x leftMargin 横坐标 可能会出现左边距 for int j 0 j col size j String jpgname String col get j ImageIcon icon new ImageIcon jpgname Image img icon getImage int imgWidth img getHeight null g drawImage img x y null x imgWidth y smallWidth g dispose FileOutputStream out new FileOutputStream picName 指定输出文件 JPEGImageEncoder encoder JPEGCodec createJPEGEncoder ou t 设置文件格式 JPEGEncodeParam param encoder getDefaultJPEGEncodeParam bufImage 从图片缓冲中读取 param setQuality 50f true encoder encode bufImage param 存盘 out flush out close catch Exception e System out println createBigJPG Failed e printStackTrace 注 1 AnimatedGifEncoder 和 GifDecoder 以及这两个类涉及到的相关类 在网 上搜索一下就可以找到 2 在 linux 系统下 如果你想支持更多系统外的字体 使用下面两句话 可以 不用为系统添加字体 直接把字体文件拷贝到相应位置即可 但是需要 jdk1 5 环境 File file new File fontPath 字体文件 Font font Font createFont Font TRUETYPE FONT file 根据字体文件 所在位置 创建新的字体对象 如果是 jdk1 5 以下版本则需要为系统添加字体 因为 createFont int fontFormat File fontFile 这个方法 是从 1 5 才开始有的 3 g setRenderingHint RenderingHints KEY ANTIALIASING RenderingHints VALUE ANTIALIAS ON 我在测试中发现 当设置的字体过大的时候 会出现很明星的锯齿 后来在网 上找到了这个解决方法 4 有了以上几个方法 就可以做出更好看的闪信了 我也是因为需求才写下这 些方法的 美工做了一些热门词汇的 gif 图片 在短信转彩信遇到这些词汇时 要使用提供的图片替换文字 AnimatedGifEncoder java 源码 处理 GIF 图片 2007 01 10 17 49 import java io import java awt import java awt image Class AnimatedGifEncoder Encodes a GIF file consisting of one or more frames Example AnimatedGifEncoder e new AnimatedGifEncoder e start outputFileName e setDelay 1000 1 frame per sec e addFrame image1 e addFrame image2 e finish No copyright asserted on the source code of this class May be us ed for any purpose however refer to the Unisys LZW patent for restr ictions on use of the associated LZWEncoder class Please forward any cor rections to kweiner author Kevin Weiner FM Software version 1 03 November 2003 public class AnimatedGifEncoder protected int width image size protected int height protected Color transparent null transparent color if given protected int transIndex transparent index in color table protected int repeat 1 no repeat protected int delay 0 frame delay hundredths protected boolean started false ready to output frames protected OutputStream out protected BufferedImage image current frame protected byte pixels BGR byte array from frame protected byte indexedPixels converted frame indexed to palett e protected int colorDepth number of bit planes protected byte colorTab RGB palette protected boolean usedEntry new boolean 256 active palette entries protected int palSize 7 color table size bits 1 protected int dispose 1 disposal code 1 use default protected boolean closeStream false close stream when finished protected boolean firstFrame true protected boolean sizeSet false if false get size from first frame protected int sample 10 default sample interval for quantizer Sets the delay time between each frame or changes it for subsequent frames applies to last frame added param ms int delay time in milliseconds public void setDelay int ms delay Math round ms 10 0f Sets the GIF frame disposal code for the last added frame and any subsequent frames Default is 0 if no transparent color has been set otherwise 2 param code int disposal code public void setDispose int code if code 0 dispose code Sets the number of times the set of GIF frames should be played Default is 1 0 means play indefinitely Must be invoked before the first image is added param iter int number of iterations return public void setRepeat int iter if iter 0 repeat iter Sets the transparent color for the last added frame and any subsequent frames Since all colors are subject to modification in the quantization process the color in the final palette for each frame closest to the given color becomes the transparent color for that frame May be set to null to indicate no transparent color param c Color to be treated as transparent on display public void setTransparent Color c transparent c Adds next GIF frame The frame is not written immediately but i s actually deferred until the next frame is received so that timing data can be inserted Invoking finish flushes all frames If setSize was not invoked the size of the first image is used for all subsequent frames param im BufferedImage containing frame to write return true if successful public boolean addFrame BufferedImage im if im null started return false boolean ok true try if sizeSet use first frame s size setSize im getWidth im getHeight image im getImagePixels convert to correct format if necessary analyzePixels build color table logical screen descriptior writePalette global color table if repeat 0 use NS app extension to indicate reps writeNetscapeExt writeGraphicCtrlExt write graphic control extension writeImageDesc image descriptor if firstFrame writePalette local color table writePixels encode and write pixel data firstFrame false catch IOException e ok false return ok Flushes any pending data and closes output file If writing to an OutputStream the stream is not closed public boolean finish if started return false boolean ok true started false try out write 0 x3b gif trailer out flush if closeStream out close catch IOException e ok false reset for subsequent use transIndex 0 out null image null pixels null indexedPixels null colorTab null closeStream false firstFrame true return ok Sets frame rate in frames per second Equivalent to setDelay 1000 fps param fps float frame rate frames per second public void setFrameRate float fps if fps 0f delay Math round 100f fps Sets quality of color quantization conversion of images to the maximum 256 colors allowed by the GIF specification Lower values minimum 1 produce better colors but slow processing significantly 10 is the default and produces good color mapping at reasonable speeds Values greater than 20 do not yield significant improvements in speed param quality int greater than 0 return public void setQuality int quality if quality 1 quality 1 sample quality Sets the GIF frame size The default size is the size of the first frame added if this method is not invoked param w int frame width param h int frame width public void setSize int w int h if started width w height h if width 1 width 320 if height 1 height 240 sizeSet true Initiates GIF file creation on the given stream The stream is not closed automatically param os OutputStream on which GIF images are written return false if initial write failed public boolean start OutputStream os if os null return false boolean ok true closeStream false out os try writeString GIF89a header catch IOException e ok false return started ok Initiates writing of a GIF file with the specified name param file String containing output file name return false if open or initial write failed public boolean start String file boolean ok true try out new BufferedOutputStream new FileOutputStream file ok start out closeStream true catch IOException e ok false return started ok Analyzes image colors and creates color map protected void analyzePixels int len pixels length int nPix len 3 indexedPixels new byte nPix NeuQuant nq new NeuQuant pixels len sample initialize quantizer colorTab nq process create reduced palette convert map from BGR to RGB for int i 0 i colorTab length i 3 byte temp colorTab i colorTab i colorTab i 2 colorTab i 2 temp usedEntry i 3 false map image pixels to new palette int k 0 for int i 0 i nPix i int index nq map pixels k usedEntry index true indexedPixels i byte index pixels null colorDepth 8 palSize 7 get closest match to transparent color if specified if transparent null transIndex findClosest transparent Returns index of palette color closest to c protected int findClosest Color c if colorTab null return 1 int r c getRed int g c getGreen int b c getBlue int minpos 0 int dmin 256 256 256 int len colorTab length for int i 0 i len int dr r colorTab i int dg g colorTab i int db b colorTab i int d dr dr dg dg db db int index i 3 if usedEntry index user override disp 2 packed fields out write 0 1 3 reserved disp 4 6 disposal 0 7 user input 0 none transp 8 transparency flag writeShort delay delay x 1 100 sec out write transIndex transparent color index out write 0 block terminator Writes Image Descriptor protected void writeImageDesc throws IOException out write 0 x2c image separator writeShort 0 image position x y 0 0 writeShort 0 writeShort width image size writeShort height packed fields if firstFrame no LCT GCT is used for first or only frame out write 0 else specify normal LCT out write 0 x80 1 local color table 1 yes 0 2 interlace 0 no 0 3 sorted 0 no 0 4 5 reserved palSize 6 8 size of color table Writes Logical Screen Descriptor protected void writeLSD throws IOException logical screen size writeShort width writeShort height packed fields out write 0 x80 1 global color table flag 1 gct used 0 x70 2 4 color resolution 7 0 x00 5 gct sort flag 0 palSize 6 8 gct size out write 0 background color index out write 0 pixel aspect ratio assume 1 1 Writes Netscape application extension to define repeat count protected void writeNetscapeExt throws IOException out write 0 x21 extension introducer out write 0 xff app extension label out write 11 block size writeString NETSCAPE 2 0 app id auth code out write 3 sub block size out write 1 loop sub block id writeShort repeat loop count extra iterations 0 repeat forev er out write 0 block terminator Writes color table protected void writePalette throws IOException out write colorTab 0 colorTab length int n 3 256 colorTab length for int i 0 i 8 Writes string to output stream protected void writeString String s throws IOException for int i 0 i 0 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 destinatio n int pass 1 int inc 8 int iline 0 for int i 0 i 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 0 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 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 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 clear pixelStack top suffix code code prefix code first int suffix code 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 available old code in code Pop a pixel off the pixel stack top pixels pi pixelStack top i for i pi i 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 al pha 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 int g int c j int b int c j tab i 0 xff000000 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 0 x2C image separator readImage break case 0 x21 extension code read switch code case 0 xf9 graphics control extension readGraphicControlExt break case 0 xff application extension readBlock String app for int i 0 i 2 disposal method if dispose 0 dispose 1 ele

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论