缩小图片工具类

   
package com.juqi.group.common.util;import java.awt.image.bufferedimage;import java.io.file;import java.io.ioexception;import javax.imageio.imageio;public class imageutil {	/**	 * 缩小图片	 * 	 * @param srcfile	 *            原图片	 * @param destfile	 *            目标图片	 * @param multiple	 *            缩略倍数       	 * @throws ioexception	 */	public static void resizefix(file srcfile, file destfile,float multiple) throws ioexception {		bufferedimage srcimgbuff = imageio.read(srcfile);		int width = srcimgbuff.getwidth();		int height = srcimgbuff.getheight();		int zoomwidth = (int)(width *multiple);		int zoomheight = (int)(height *multiple);		bufferedimage imgbuff = scaleimage(srcimgbuff, width, height,				zoomwidth, zoomheight);		writefile(imgbuff, destfile);	}		public static void writefile(bufferedimage imgbuf, file destfile)			throws ioexception {		file parent = destfile.getparentfile();		if (!parent.exists()) {			parent.mkdirs();		}		imageio.write(imgbuf, "jpeg", destfile);	}	private static bufferedimage scaleimage(bufferedimage srcimgbuff,			int width, int height, int zoomwidth, int zoomheight) {		int[] colorarray = srcimgbuff.getrgb(0, 0, width, height, null, 0,				width);		bufferedimage outbuff = new bufferedimage(zoomwidth, zoomheight,				bufferedimage.type_int_rgb);		// 宽缩小的倍数		float wscale = (float) width / zoomwidth;		int wscaleint = (int) (wscale + 0.5);		// 高缩小的倍数		float hscale = (float) height / zoomheight;		int hscaleint = (int) (hscale + 0.5);		int area = wscaleint * hscaleint;		int x0, x1, y0, y1;		int color;		long red, green, blue;		int x, y, i, j;		for (y = 0; y < zoomheight; y++) {			// 得到原图高的y坐标			y0 = (int) (y * hscale);			y1 = y0 + hscaleint;			for (x = 0; x < zoomwidth; x++) {				x0 = (int) (x * wscale);				x1 = x0 + wscaleint;				red = green = blue = 0;				for (i = x0; i < x1; i++) {					for (j = y0; j < y1; j++) {						color = colorarray[width * j + i];						red += getredvalue(color);						green += getgreenvalue(color);						blue += getbluevalue(color);					}				}				outbuff.setrgb(x, y, comrgb((int) (red / area),						(int) (green / area), (int) (blue / area)));			}		}		return outbuff;	}	private static int getredvalue(int rgbvalue) {		return (rgbvalue &amp; 0x00ff0000) >> 16;	}	private static int getgreenvalue(int rgbvalue) {		return (rgbvalue &amp; 0x0000ff00) >> 8;	}	private static int getbluevalue(int rgbvalue) {		return rgbvalue &amp; 0x000000ff;	}	private static int comrgb(int redvalue, int greenvalue, int bluevalue) {		return (redvalue << 16) + (greenvalue << 8) + bluevalue;	}	public static void main(string[] args) throws exception {		long time = system.currenttimemillis();		imageutil.resizefix(new file("e:\\pic\\mark.jpg"), new file("e:\\pic\\mark_2.jpg") , 1/2f);		imageutil.resizefix(new file("e:\\pic\\mark.jpg"), new file("e:\\pic\\mark_4.jpg") , 1/4f);		time = system.currenttimemillis() - time;		system.out.println("resize2 img in " + time + "ms");	}}
 

你可能感兴趣的:(java,工作)