【Jsp精品源码栏目提醒】:网学会员为需要Jsp精品源码的朋友们搜集整理了【精品文档】java jsp 图片处理,水印,缩放,放大,叠加等功能 - 其它管理文献相关资料,希望对各位网友有所帮助!
这几天一直在做图片处理其中遇到了一些问题在网上也找到了解决办法虽然不是最佳的在这里还是作个记录吧。
1 多张jpg图合成gif动画 / 把多张jpg图片合成一张 param pic String 多个jpg文件名 包含路径 param newPic String 生成的gif文件名 包含路径 / private synchronized void jpgToGifString pic String newPic try AnimatedGifEncoder e new AnimatedGifEncoder //网上可以找到此类 e.setRepeat0 e.startnewPic BufferedImage src new BufferedImagepic.length for int i 0 i lt src.length i e.setDelay200 //设置播放的延迟时间 srci ImageIO.readnew Filepici // 读入需要播放的jpg文件 e.addFramesrci //添加到帧中 e.finish catch Exception e System.out.println quotjpgToGif Failed:quot e.printStackTrace 2 gif动画分解成多张jpg / 把gif图片按帧拆分成jpg图片 param gifName String 小gif图片路径名称 param path String 生成小jpg图片的路径 return String 返回生成小jpg图片的名称 / private synchronized String splitGifString gifNameString path try GifDecoder decoder new GifDecoder decoder.readgifName int n decoder.getFrameCount //得到frame的个数 String subPic new Stringn String tag this.getTag for int i 0 i lt n i BufferedImage frame decoder.getFramei //得到帧 //int delay decoder.getDelayi //得到延迟时间 //生成小的JPG文件 subPici path String.valuei quot.jpgquot FileOutputStream out new FileOutputStreamsubPici ImageIO.writeframe quotjpegquot out JPEGImageEncoder encoder JPEGCodec.createJPEGEncoderout encoder.encodeframe //存盘 out.flush out.close return subPic catch Exception e System.out.println quotsplitGif Failedquot 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 createJpgByFontString s int smallWidthColor bgcolorColor fontcolorString fontPathString jpgname try //宽度 高度 BufferedImage bimage new BufferedImages.lengthsmallWidth smallWidthBufferedImage.TYPE_INT_RGB Graphics2D g bimage.createGraphics g.setColorbgcolor //背景色 g.fillRect0 0 smallWidth smallWidth //画一个矩形 g.setRenderingHintRenderingHints.KEY_ANTIALIASINGRenderingHints.VALUE_ANTIALIAS_ON //去除锯齿当设置的字体过大的时候会出现锯齿 g.setColorfontcolor //字的颜色 File file new FilefontPath //字体文件 Font font Font.createFontFont.TRUETYPE_FONT file //根据字体文件所在位置创建新的字体对象此语句在jdk1.5下面才支持 g.setFontfont.deriveFontfloat smallWidth //font.deriveFontfloat f复制当前 Font 对象并应用新设置字体的大小 g.drawStrings0 smallWidth //在指定坐标除添加文字 g.dispose FileOutputStream out new FileOutputStreamjpgname //指定输出文件 JPEGImageEncoder encoder JPEGCodec.createJPEGEncoderout JPEGEncodeParam param encoder.getDefaultJPEGEncodeParambimage param.setQuality50f true encoder.encodebimage param //存盘 out.flush out.close catch Exception e System.out.println quotcreateJpgByFont Failedquot e.printStackTrace 4 多张小jpg图合成一张大JPG图在这里对大图只作宽度限制不做高度限制 / 将多个小图片合成一张大jpg图 小的jpg图片按照行列顺序平铺 param smallJPG ArrayList 一组小的jpg图片 param bigWidth int 大图宽度 param smallWidth int 单个文字生成的小图的宽度和高度是一致的 return / private void createBigJPGArrayList smallJPG int bigWidth int smallHeighColor bgColor String picName try if bigWidth lt 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 BufferedImagesetWidth setHeight BufferedImage.TYPE_INT_RGB Graphics2D g bufImage.createGraphics g.setColorbgColor //背景的颜色 g.fillRect0 0 setWidth setHeight int y 0 //纵坐标 for int i 0 i lt rowCount i //遍历每行 ArrayList col ArrayList smallJPG.geti int x leftMargin //横坐标 可能会出现左边距 for int j 0 j lt col.size j String jpgname String col.getj ImageIcon icon new ImageIconjpgname Image img icon.getImage int imgWidth img.getHeightnull g.drawImageimg x y null x imgWidth y smallWidth g.dispose FileOutputStream out new FileOutputStreampicName //指定输出文件 JPEGImageEncoder encoder JPEGCodec.createJPEGEncoderout //设置文件格式 JPEGEncodeParam param encoder.getDefaultJPEGEncodeParambufImage //从图片缓冲中读取 param.setQuality50f true encoder.encodebufImage param //存盘 out.flush out.close catch Exception e System.out.println quotcreateBigJPG Failedquot e.printStackTrace 注 1AnimatedGifEncoder和GifDecoder以及这两个类涉及到的相关类在网上搜索一下就可以找到。
2在linux系统下如果你想支持更多系统外的字体使用下面两句话可以不用为系统添加字体直接把字体文件拷贝到相应位置即可但是需要jdk1.5环境。
File file new FilefontPath //字体文件 Font font Font.createFontFont.TRUETYPE_FONT file //根据字体文件所在位置创建新的字体对象 如果是jdk1.5以下版本则需要为系统添加字体因为createFontint fontFormat File fontFile 这个方法是从1.5才开始有的。
3g.setRenderingHintRenderingHints.KEY_ANTIALIASINGRenderingHints.VALUE_ANTIALIAS_ON 我在测试中发现当设置的字体过大的时候会出现很明星的锯齿后来在网上找到了这个解决方法。
4有了以上几个方法就可以做出更好看的闪信了。
我也是因为需求才写下这些方法的美工做了一些热门词汇的gif图片在短信转彩信遇到这些词汇时要使用提供的图片替换文字。
以下是 LZWEncoder.java //LZWEncoder.java
源码处理GIF图片 import java.io.OutputStream import java.io.IOException // // Adapted from Jef Poskanzers Java port by way of J. M. G. Elliott. // K Weiner 12/00 class LZWEncoder private static final int EOF -1 private int imgW imgH private byte pixAry private int initCodeSize private int remaining private int curPixel // GIFCOMPR.C - GIF Image compression routines // // Lempel-Ziv compression based on compress. GIF modifications by // David Rowley mgardiwatdcsu.waterloo.edu // General DEFINEs static final int BITS 12 static final int HSIZE 5003 // 80 occupancy // GIF Image compression - modified compress // // Based on: compress.c - File compression ala IEEE Computer June 1984. // // By Authors: Spencer W. Thomas decvaxharpoutah-csutah-grthomas // Jim McKie decvaxmcvaxjim // Steve Davies decvaxvax135petsdpeorasrd // Ken Turkowski decvaxdecwrlturtlevaxken // James A. Woods decvaxihnp4amesjaw // Joe Orost decvaxvax135petsdjoe int n_bits // number of bits/code int maxbits BITS // user settable max bits/code int maxcode // maximum code given n_bits int maxmaxcode 1 int htab new intHSIZE int codetab new intHSIZE int hsize HSIZE // for dynamic table sizing int free_ent 0 // first unused entry // block compression parameters -- after all codes are used up // and compression rate changes start over. boolean clear_flg false // Algorithm: use open addressing double hashing no chaining on the // prefix code / next character combination. We do a variant of Knuths // algorithm D vol. 3 sec. 6.4 along with G. Knotts relatively-prime // secondary probe. Here the modular division first probe is gives way // to a faster exclusive-or manipulation. Also do block compression with // an adaptive reset whereby the code table is cleared when the compression // ratio decreases but after the table fills. The variable-length output // codes are re-sized at this point and a special CLEAR code is generated // for the decompressor. Late addition: construct the table according to // file size for noticeable speed improvement on small files. Please direct // questions about this implementation to amesjaw. int g_init_bits int ClearCode int EOFCode // output // // Output the given code. // Inputs: // code: A n_bits-bit integer. If -1 then EOF. This assumes // that n_bits lt wordsize - 1. // Outputs: // Outputs code to the file. // Assumptions: // Chars are 8 bits long. // Algorithm: // Maintain a BITS character long buffer so that 8 codes will // fit in it exactly. Use the VAX insv instruction to insert each // code in turn. When the buffer fills up empty it and start over. int cur_accum 0 int cur_bits 0 int masks 0x0000 0x0001 0x0003 0x0007 0x000F 0x001F 0x003F 0x007F 0x00FF 0x01FF 0x03FF 0x07FF 0x0FFF 0x1FFF 0x3FFF 0x7FFF 0xFFFF // Number of characters so far in this packet int a_count // Define the storage for the packet accumulator byte accum new byte256 //---------------------------------------------------------------------------- LZWEncoderint width int height byte pixels int color_depth imgW width imgH height pixAry pixels initCodeSize Math.max2 color_depth // Add a character to the end of the current packet and if it is 254 // characters flush the packet to disk. void char_outbyte c OutputStream outs throws IOException accuma_count c if a_count gt 254 flush_charouts // Clear out the hash table // table clear for block compress void cl_blockOutputStream outs throws IOException cl_hashhsize free_ent ClearCode 2 clear_flg true outputClearCode outs // reset code table void cl_hashint hsize for int i 0 i lt hsize i htabi -1 void compressint init_bits OutputStream outs throws IOException int fcode int i / 0 / int c int ent int disp int hsize_reg int hshift // Set up the globals: g_init_bits - initial number of bits g_init_bits init_bits // Set up the necessary values clear_flg false n_bits g_init_bits maxcode MAXCODEn_bits ClearCode 1 EOFCode ClearCode 1 free_ent ClearCode 2 a_count 0 // clear packet ent nextPixel hshift 0 for fcode hsize fcode lt 65536 fcode 2 hshift hshift 8 - hshift // set hash code range bound hsize_reg hsize cl_hashhsize_reg // clear hash table outputClearCode outs outer_loop : while c nextPixel EOF fcode c i c if htabi fcode ent codetabi continue else if htabi gt 0 // non-empty slot disp hsize_reg - i // secondary hash after G. Knott if i 0 disp 1 do if i - disp lt 0 i hsize_reg if htabi fcode ent codetabi continue outer_loop while htabi gt 0 outputent outs ent c if free_ent lt maxmaxcode codetabi free_ent // code -gt hashtable htabi fcode else cl_blockouts // Put out the final code. outputent outs outputEOFCode outs //---------------------------------------------------------------------------- void encodeOutputStream os throws IOException os.writeinitCodeSize // write quotinitial code sizequot byte remaining imgW imgH // reset navigation variables curPixel 0 compressinitCodeSize 1 os // compress and write the pixel data os.write0 // write block terminator // Flush the packet to disk and reset the accumulator void flush_charOutputStream outs throws IOException if a_count gt 0 outs.writea_count outs.writeaccum 0 a_count a_count 0 final int MAXCODEint n_bits return 1 //---------------------------------------------------------------------------- // Return the next pixel from the image //---------------------------------------------------------------------------- private int nextPixel if remaining 0 return EOF --remaining byte pix pixArycurPixel return pix amp 0xff void outputint code OutputStream outs throws IOException cur_accum amp maskscur_bits if cur_bits gt 0 cur_accum code else cur_accum code cur_bits n_bits while cur_bits gt 8 char_outbyte cur_accum amp 0xff outs cur_accum gtgt 8 cur_bits - 8 // If the next entry is going to be too big for the code size // then increase it if possible. if free_ent gt maxcode clear_flg if clear_flg maxcode MAXCODEn_bits g_init_bits clear_flg false else n_bits if n_bits maxbits maxcode maxmaxcode else maxcode MAXCODEn_bits if code EOFCode // At EOF write the rest of the buffer. while cur_bits gt 0 char_outbyte cur_accum amp 0xff outs cur_accum gtgt 8 cur_bits - 8 flush_charouts 以下是NeuQuant.java //NeuQuant.java
源码处理GIF图片 / NeuQuant Neural-Net Quantization Algorithm ------------------------------------------ Copyright c 1994 Anthony Dekker NEUQUANT Neural-Net quantization algorithm by Anthony Dekker 1994. See quotKohonen neural networks for optimal colour quantizationquot in quotNetwork: Computation in Neural Systemsquot Vol. 5 1994 pp 351-367. for a discussion of the algorithm. Any party obtaining a copy of these files from the author directly or indirectly is granted free of charge a full and unrestricted irrevocable world-wide paid up royalty-free nonexclusive right and license to deal in this software and documentation files the quotSoftwarequot including without limitation the rights to use copy modify merge publish distribute sublicense and/or sell copies of the Software and to permit persons who receive copies from any such party to do so with the only requirement being that this copyright notice remain intact. / // Ported to Java 12/00 K Weiner public class NeuQuant protected static final int netsize 256 / number of colours used / / four primes near 500 - assume no image has a length so large / / that it is divisible by all four primes / protected static final int prime1 499 protected static final int prime2 491 protected static final int prime3 487 protected static final int prime4 503 protected static final int minpicturebytes 3 prime4 / minimum size for input image / / Program Skeleton ---------------- select samplefac in range 1..30 read image from input file pic unsigned char malloc3widthheight initnetpic3widthheightsamplefac learn unbiasnet write output image header using writecolourmapf inxbuild write output image using inxsearchbgr / / Network Definitions ------------------- / protected static final int maxnetpos netsize - 1 protected static final int netbiasshift 4 / bias for colour values / protected static final int ncycles 100 / no. of learning cycles / / defs for freq and bias / protected static final int intbiasshift 16 / bias for fractions / protected static final int intbias int 1 protected static final int gammashift 10 / gamma 1024 / protected static final int gamma int 1 protected static final int betashift 10 protected static final int beta intbias gtgt betashift / beta 1/1024 / protected static final int betagamma intbias / defs for decreasing radius factor / protected static final int initrad netsize gtgt 3 / for 256 cols radius starts / protected static final int radiusbiasshift 6 / at 32.0 biased by 6 bits / protected static final int radiusbias int 1 protected static final int initradius initrad radiusbias / and decreases by a / protected static final int radiusdec 30 / factor of 1/30 each cycle / / defs for decreasing alpha factor / protected static final int alphabiasshift 10 / alpha starts at 1.0 / protected static final int initalpha int 1 protected int alphadec / biased by 10 bits / / radbias and alpharadbias used for radpower calculation / protected static final int radbiasshift 8 protected static final int radbias int 1 protected static final int alpharadbshift alphabiasshift radbiasshift protected static final int alpharadbias int 1.
上一篇:
【精品】java连接数据库及数据库的查询
下一篇:
小学英语作文:讨厌的蟑螂(双语)