java制作图片的缩略图

package com.mxo9.b2c.service.administration.impl.goodstrading.goods;

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class AlterUploadImage {
	String inputDir; //源图片的绝对路径,不包含图片的文件名
	String outputDir; //目标图片的绝对路径,不包含图片的文件名
	String inputFileName; //源图片文件名
	String outputFileName; //目标图片的文件名
	int outputWidth; //目标图片的宽
	int outputHeight; //目标图片的高
	boolean proportion = true; //是否等比例缩放
	private String inputFileUrl;//源图片的绝对路径,包含文件名
	private String outputFileUrl;//目标图片的绝对路径,包含文件名
	private String tempUrl;
	/**
	 * 初始化修改图片大小的参数
	 * @param inputDir 源图片的绝对路径,不包含图片的文件名
	 * @param outputDir 目标图片的绝对路径,不包含图片的文件名
	 * @param inputFileName 源图片文件名
	 * @param outputFileName 目标图片的文件名
	 * @param outputWidth 目标图片的宽
	 * @param outputHeight 目标图片的高
	 * @param proportion 是否等比例缩放
	 */
	public AlterUploadImage(String inputDir, String outputDir,
			String inputFileName, String outputFileName, int outputWidth,
			int outputHeight, boolean proportion) {
		this.inputDir=inputDir;
		this.outputDir=outputDir;
		this.inputFileName= inputFileName;
		this.outputFileName=outputFileName;
		this.outputWidth=outputWidth;
		this.outputHeight=outputHeight;
		this.proportion=proportion;
	}

	public AlterUploadImage() {
		inputDir="";
		outputDir="";
		inputFileName="";
		outputFileName="";
		outputWidth=100;
		outputHeight=100;
		proportion=true;
	}

	public boolean alterImageSize() throws IOException {
		//构造源、目标图片的路径
		inputFileUrl=inputDir+inputFileName;
		outputFileUrl=outputDir+outputFileName;
		createDir(outputDir);
		try { 
	        Image image = javax.imageio.ImageIO.read(new File(inputFileUrl)); 
	        int imageWidth = image.getWidth(null); 
	        int imageHeight = image.getHeight(null); 
	        float scale = getRatio(imageWidth,imageHeight,outputWidth,outputHeight); 
	        imageWidth = (int)(scale*imageWidth); 
	        imageHeight = (int)(scale*imageHeight); 
	         
	        image = image.getScaledInstance(imageWidth, imageHeight, Image.SCALE_AREA_AVERAGING); 
	        // Make a BufferedImage from the Image. 
	        BufferedImage mBufferedImage = new BufferedImage(imageWidth, imageHeight,BufferedImage.TYPE_INT_RGB); 
	        Graphics2D g2 = mBufferedImage.createGraphics();
	        g2.drawImage(image, 0, 0,imageWidth, imageHeight, Color.white,null); 
	        g2.dispose(); 
	         
	        float[] kernelData2 = {-0.125f,-0.125f,-0.125f,-0.125f,2,-0.125f,-0.125f,-0.125f,-0.125f}; 
	        Kernel kernel = new Kernel(3, 3, kernelData2); 
	        ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null); 
	        mBufferedImage = cOp.filter(mBufferedImage, null); 

	        FileOutputStream out = new FileOutputStream(outputFileUrl);
	        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); 
	        encoder.encode(mBufferedImage); 
	        out.close(); 
	        return true;
	    }catch (Exception ioe){ 
	    	return false;
	    }
	    finally{
	    } 
		//return ThumbnailUtil.creatThumbnail(inputFileUrl, outputFileUrl, outputWidth, outputHeight);
//		File fileOut = new File(tempUrl);
//		File fileIn = new File(inputFileUrl);
//		FileOutputStream tempout = null;
//		try {
//			tempout = new FileOutputStream(fileOut);
//		} catch (Exception ex) {
//			System.out.println(ex.toString());
//		}
//		Image img = null;
//		Applet app = new Applet();
//		MediaTracker mt = new MediaTracker(app);
//		try {
//			img = javax.imageio.ImageIO.read(fileIn);
//			mt.addImage(img, 0);
//			mt.waitForID(0);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		if (img.getWidth(null) == -1) {
//			return false;
//		} else {
//			int new_w;
//			int new_h;
//			if (this.proportion == true) {//判断是否等比例缩放
//				//计算比率
//				double rate1 = ((double) img.getWidth(null)) / (double) outputWidth + 0.1;
//				double rate2 = ((double) img.getHeight(null)) / (double) outputHeight + 0.1;
//				double rate = rate1 > rate2 ? rate1 : rate2;
//				new_w = (int) (((double) img.getWidth(null)) / rate);
//				new_h = (int) (((double) img.getHeight(null)) / rate);
//			} else {
//				new_w = outputWidth; //宽
//				new_h = outputHeight; //高
//			}
//			BufferedImage buffImg = new BufferedImage(new_w, new_h,
//					BufferedImage.TYPE_INT_RGB);
//
//			Graphics g = buffImg.createGraphics();
//
//			g.setColor(Color.white);
//			g.fillRect(0, 0, new_w, new_h);
//
//			g.drawImage(img, 0, 0, new_w, new_h, null);
//			g.dispose();
//			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(tempout);
//			try {
//				encoder.encode(buffImg);
//				tempout.close();
//			} catch (IOException ex) {
//				System.out.println(ex.toString());
//			}
//		}
//		createThumbImg(outputWidth,outputHeight);
//		fileOut.delete();
//		return true;
	}
	
	public static float getRatio(int width,int height,int maxWidth,int maxHeight){ 
	    float Ratio = 1.0f; 
	    float widthRatio ; 
	    float heightRatio ; 
	    widthRatio = (float)maxWidth/width; 
	    heightRatio = (float)maxHeight/height; 
	    if(widthRatio<1.0 || heightRatio<1.0){ 
	      Ratio = widthRatio<=heightRatio?widthRatio:heightRatio; 
	    } 
	    return Ratio; 
	  }
	
	//文亮,2009/07/15
	public boolean alterImageSizeForFriendLink() throws IOException {
		//构造源、目标图片的路径
		inputFileUrl=inputDir+inputFileName;
		outputFileUrl=outputDir+outputFileName;
		tempUrl=outputDir+outputFileName;
		createDir(tempUrl);
		File fileOut = new File(tempUrl);
		File fileIn = new File(inputFileUrl);
		FileOutputStream tempout = null;
		try {
			tempout = new FileOutputStream(fileOut);
		} catch (Exception ex) {
			System.out.println(ex.toString());
		}
		Image img = null;
		Applet app = new Applet();
		MediaTracker mt = new MediaTracker(app);
		try {
			img = javax.imageio.ImageIO.read(fileIn);
			mt.addImage(img, 0);
			mt.waitForID(0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (img.getWidth(null) == -1) {
			return false;
		} else {
			int new_w;
			int new_h;
			if (this.proportion == true) {//判断是否等比例缩放
				//计算比率
				double rate1 = ((double) img.getWidth(null)) / (double) outputWidth + 0.1;
				double rate2 = ((double) img.getHeight(null)) / (double) outputHeight + 0.1;
				double rate = rate1 > rate2 ? rate1 : rate2;
				new_w = (int) (((double) img.getWidth(null)) / rate);
				new_h = (int) (((double) img.getHeight(null)) / rate);
			} else {
				new_w = outputWidth; //宽
				new_h = outputHeight; //高
			}
			BufferedImage buffImg = new BufferedImage(new_w, new_h,
					BufferedImage.TYPE_INT_RGB);

			Graphics g = buffImg.createGraphics();

			//g.setColor(Color.white);
			g.fillRect(0, 0, new_w, new_h);

			g.drawImage(img, 0, 0, new_w, new_h, null);
			g.dispose();
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(tempout);
			try {
				encoder.encode(buffImg);
				tempout.close();
			} catch (IOException ex) {
				System.out.println(ex.toString());
			}
		}
		return true;
	}
	
	//文亮,2009/07/15,图片批量处理
	public boolean alterImageSizeForPicBatch() throws IOException {
		//构造源、目标图片的路径
		inputFileUrl=inputDir+inputFileName;
		outputFileUrl=outputDir+outputFileName;
		tempUrl=outputDir+"temp"+outputFileName;
		createDir(tempUrl);
		File fileOut = new File(tempUrl);
		File fileIn = new File(inputFileUrl);
		FileOutputStream tempout = null;
		try {
				tempout = new FileOutputStream(fileOut);
		} catch (Exception ex) {
			System.out.println(ex.toString());
		}
		Image img = null;
		Applet app = new Applet();
		MediaTracker mt = new MediaTracker(app);
		try {
			img = javax.imageio.ImageIO.read(fileIn);
			mt.addImage(img, 0);
			mt.waitForID(0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (img.getWidth(null) == -1) {
			return false;
		} else {
			int new_w;
			int new_h;
			if (this.proportion == true) {//判断是否等比例缩放
				//计算比率
				double rate1 = ((double) img.getWidth(null)) / (double) outputWidth + 0.1;
				double rate2 = ((double) img.getHeight(null)) / (double) outputHeight + 0.1;
				double rate = rate1 > rate2 ? rate1 : rate2;
				new_w = (int) (((double) img.getWidth(null)) / rate);
				new_h = (int) (((double) img.getHeight(null)) / rate);
			} else {
				new_w = outputWidth; //宽
				new_h = outputHeight; //高
			}
			BufferedImage buffImg = new BufferedImage(new_w, new_h,
					BufferedImage.TYPE_INT_RGB);

			Graphics g = buffImg.createGraphics();

			g.setColor(Color.white);
			g.fillRect(0, 0, new_w, new_h);

			g.drawImage(img, 0, 0, new_w, new_h, null);
			g.dispose();
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(tempout);
			try {
				encoder.encode(buffImg);
				tempout.close();
			} catch (IOException ex) {
				System.out.println(ex.toString());
			}
		}
		//createThumbImg(outputWidth,outputHeight);
		//fileOut.delete();
		return true;
	}
	
	/**
	 * 该方法用于对生成的图片进一步处理,处理的要求就是创建一个高度为参数outputHeight宽度为outputWidth的图像,其背景色为白色,然后将生成的图片放在该图像的中央
	 * 以创建一张新图片
	 * @param width 新图片的宽度
	 * @param height 新图片的高度
	 * @throws IOException
	 */
	public void createThumbImg(int width,int height) throws IOException{
		int startX=0;
		int startY=0;
		int[] ImageArrayOne=new int[width*height];
  	  	for(int i=0;i<ImageArrayOne.length;i++){
  	  		ImageArrayOne[i]=Color.WHITE.getRGB();
  	  	}
		//对第二张图片做相同的处理
        File fileTwo = new File(tempUrl);
        BufferedImage ImageTwo = ImageIO.read(fileTwo);
        int imgWidth = ImageTwo.getWidth();//图片宽度
        int imgHeight = ImageTwo.getHeight();//图片高度
        int[] ImageArray = new int[imgWidth*imgHeight];
        ImageArray = ImageTwo.getRGB(0,0,imgWidth,imgHeight,ImageArray,0,imgWidth);
		startX=(width-imgWidth)/2;
        startY=(height-imgHeight)/2;
        //生成新图片
        BufferedImage ImageNew = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        ImageNew.setRGB(0,0,width,height,ImageArrayOne,0,width);//设置背景色为白色
        ImageNew.setRGB(startX,startY,imgWidth,imgHeight,ImageArray,0,imgWidth);//将缩略图置于最上面
        File outFile = new File(outputFileUrl);
        ImageIO.write(ImageNew, outputFileUrl.substring(outputFileUrl.lastIndexOf(".")+1), outFile);//写图片
	}
	
	private void createDir(String path){
		String realPath;
		try{
			realPath=path.substring(0,path.lastIndexOf("/"));
		}
		catch(Exception e){
			realPath=path.substring(0,path.lastIndexOf("\\"));
		}
		File dir=new File(realPath);
		dir.mkdirs();
	}

	public String getInputDir() {
		return inputDir;
	}

	public void setInputDir(String inputDir) {
		this.inputDir = inputDir;
	}

	public String getOutputDir() {
		return outputDir;
	}

	public void setOutputDir(String outputDir) {
		this.outputDir = outputDir;
	}

	public String getInputFileName() {
		return inputFileName;
	}

	public void setInputFileName(String inputFileName) {
		this.inputFileName = inputFileName;
	}

	public String getOutputFileName() {
		return outputFileName;
	}

	public void setOutputFileName(String outputFileName) {
		this.outputFileName = outputFileName;
	}

	public int getOutputWidth() {
		return outputWidth;
	}

	public void setOutputWidth(int outputWidth) {
		this.outputWidth = outputWidth;
	}

	public int getOutputHeight() {
		return outputHeight;
	}

	public void setOutputHeight(int outputHeight) {
		this.outputHeight = outputHeight;
	}

	public boolean isProportion() {
		return proportion;
	}

	public void setProportion(boolean proportion) {
		this.proportion = proportion;
	}

	public String getInputFileUrl() {
		return inputFileUrl;
	}

	public void setInputFileUrl(String inputFileUrl) {
		this.inputFileUrl = inputFileUrl;
	}

	public String getOutputFileUrl() {
		return outputFileUrl;
	}

	public void setOutputFileUrl(String outputFileUrl) {
		this.outputFileUrl = outputFileUrl;
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值