关闭

JAVA生成缩略图

145人阅读 评论(0) 收藏 举报

本文来源于http://wing929.iteye.com/blog/185508,方法1中在原有的基础上增加了文件生成,及目录的生成,并且增加了以文件类型的参数的方法的重载,在服务器上传过程中可以用到。

 

方法1:[第一种方法比后一种生成的缩略图要清晰]

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.awt.*;
import java.awt.geom.AffineTransform;

import java.io.File;
import java.io.IOException;

public class ImageTest {
	public static BufferedImage resize(BufferedImage source, int targetW,
			int targetH) {
		// targetW,targetH分别表示目标长和宽
		int type = source.getType();
		BufferedImage target = null;
		double sx = (double) targetW / source.getWidth();
		double sy = (double) targetH / source.getHeight();
		// 这里想实现在targetW,targetH范围内实现等比缩放。如果不需要等比缩放
		// 则将下面的if else语句注释即可
		if (sx > sy) {
			sx = sy;
			targetW = (int) (sx * source.getWidth());
		} else {
			sy = sx;
			targetH = (int) (sy * source.getHeight());
		}
		if (type == BufferedImage.TYPE_CUSTOM) { // handmade
			ColorModel cm = source.getColorModel();
			WritableRaster raster = cm.createCompatibleWritableRaster(targetW,
					targetH);
			boolean alphaPremultiplied = cm.isAlphaPremultiplied();
			target = new BufferedImage(cm, raster, alphaPremultiplied, null);
		} else
			target = new BufferedImage(targetW, targetH, type);
		Graphics2D g = target.createGraphics();
		// smoother than exlax:
		g.setRenderingHint(RenderingHints.KEY_RENDERING,
				RenderingHints.VALUE_RENDER_QUALITY);
		g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
		g.dispose();
		return target;
	}

	/**
	 * @param fromFileStr
	 * @param saveToFileStr
	 * @param width 图片宽度
	 * @param hight 图片长度
	 * @throws Exception
	 */
	public static void saveImageAsJpg(String fromFileStr, String saveToFileStr,
			int width, int hight) throws Exception {
		BufferedImage srcImage;
		// String ex =
		// fromFileStr.substring(fromFileStr.indexOf("."),fromFileStr.length());
		String imgType = "JPEG";
		if (fromFileStr.toLowerCase().endsWith(".png")) {
			imgType = "PNG";
		}
		// System.out.println(ex);
		File saveFile = new File(saveToFileStr);
		File fromFile = new File(fromFileStr);
		srcImage = ImageIO.read(fromFile);
		if (width > 0 || hight > 0) {
			srcImage = resize(srcImage, width, hight);
		}
		ImageIO.write(srcImage, imgType, saveFile);

	}
	
	/**
	 * 以JPG格式保存文件
	 * @param srcFile 原文件
	 * @param destFile 要保存到的文件
	 * @param width 图片宽度
	 * @param hight 图片长度
	 * @throws Exception
	 */
	public static void saveImageAsJpg(File srcFile, File destFile,
			int width, int hight) throws Exception {
		BufferedImage srcImage;
		String imgType = "JPEG";
		if (srcFile.getName().toLowerCase().endsWith(".png")) {
			imgType = "PNG";
		}
		srcImage = ImageIO.read(srcFile);
		if (width > 0 || hight > 0) {
			srcImage = resize(srcImage, width, hight);
		}
		ImageIO.write(srcImage, imgType, destFile);

	}

	public static void main(String argv[]) {
		try {
			// 参数1(from),参数2(to),参数3(宽),参数4(高)
//			ImageTest.saveImageAsJpg("E:/Document/My Pictures/3.gif",
//					"c:/6.gif", 50, 50);
			String fileName = "蓝.png";
			String srcFileName = "D:/20120201/"+fileName;
			String destFileName = "D:/TESTIMAGE/IMAGE/"+fileName;
			File srcFile = new File(srcFileName);
			File destFile = createFile(destFileName, "/");
			ImageTest.saveImageAsJpg(srcFile,destFile, 350, 350);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 生成文件路径以及文件
	 * @param path文件路径+文件名
	 * @param separate文件路径分隔标识,如/
	 * @return
	 */
	public static File createFile(String path, String separate) {
		createDir(path ,separate);
		File file = new File(path);
		try {
			if (file.exists()) {
				file.delete();
			}
			file.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return file;
	}

	/**
	 * 生成文件目录
	 * @param path 如果传入的是目录,结尾必须以文件分隔符结尾
	 * @param separate
	 */
	public static void createDir(String path, String separate) {
		String filePath = path.substring(0, path.lastIndexOf(separate));
		File dir = new File(filePath);
		if (!dir.exists()) {
			createDir(filePath, separate);
			dir.mkdir();
		}
	}

}


 


 方法2:

 import java.io.*;
 import java.util.*;
 import com.sun.image.codec.jpeg.*;
 import java.awt.image.*;
 import java.awt.*;
 import java.net.*;
 import java.applet.*;
 import java.sql.*;

//缩略图类,
//本java类能将jpg图片文件,进行等比或非等比的大小转换。
//具体使用方法
//s_pic(大图片路径,生成小图片路径,大图片文件名,生成小图片文名,生成小图片宽度,生成小图片高度,是否等比缩放(默认为true))
 public class Tes {
 String InputDir; //输入图路径
 String OutputDir; //输出图路径
 String InputFileName; //输入图文件名
 String OutputFileName; //输出图文件名
 int OutputWidth = 80; //默认输出图片宽
 int OutputHeight = 80; //默认输出图片高
 int rate = 0;
 boolean proportion = true; //是否等比缩放标记(默认为等比缩放)

 public Tes() {
//初始化变量
 InputDir = "";
 OutputDir = "";
 InputFileName = "";
 OutputFileName = "";
 OutputWidth = 80;
 OutputHeight = 80;
 rate = 0;
 }

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

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

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

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

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

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

 public void setW_H(int width, int height) {
 this.OutputWidth = width;
 this.OutputHeight = height;
 }

 public String s_pic() {
 BufferedImage image;
 String NewFileName;
//建立输出文件对象
 File file = new File(OutputDir + OutputFileName);
 FileOutputStream tempout = null;
 try {
 tempout = new FileOutputStream(file);
 } catch (Exception ex) {
 System.out.println(ex.toString());
 }
 Image img = null;
 Toolkit tk = Toolkit.getDefaultToolkit();
 Applet app = new Applet();
 MediaTracker mt = new MediaTracker(app);
 try {
 img = tk.getImage(InputDir + InputFileName);
 mt.addImage(img, 0);
 mt.waitForID(0);
 } catch (Exception e) {
 e.printStackTrace();
 }

 if (img.getWidth(null) == -1) {
 System.out.println(" can't read,retry!" + "<BR>");
 return "no";
 } 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 "ok";
 }

 public String s_pic(String InputDir, String OutputDir, String InputFileName,
 String OutputFileName) {
//输入图路径
 this.InputDir = InputDir;
//输出图路径
 this.OutputDir = OutputDir;
//输入图文件名
 this.InputFileName = InputFileName;
//输出图文件名
 this.OutputFileName = OutputFileName;
 return s_pic();
 }

 public String s_pic(String InputDir, String OutputDir, String InputFileName,
 String OutputFileName, int width, int height,
 boolean gp) {
//输入图路径
 this.InputDir = InputDir;
//输出图路径
 this.OutputDir = OutputDir;
//输入图文件名
 this.InputFileName = InputFileName;
//输出图文件名
 this.OutputFileName = OutputFileName;
//设置图片长宽
 setW_H(width, height);
//是否是等比缩放 标记
 this.proportion = gp;
 return s_pic();
 }

 public static void main(String[] a) {
//s_pic(大图片路径,生成小图片路径,大图片文件名,生成小图片文名,生成小图片宽度,生成小图片高度)
 Tes mypic = new Tes();
 System.out.println(
 mypic.s_pic("E:\Document\My Pictures\",
 "E:\Document\My Pictures\",
 "topbg-3.gif", "3.gif", 400, 400, true)
 );

 }
 }


 

原文地址

http://wing929.iteye.com/blog/185508

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:40432次
    • 积分:824
    • 等级:
    • 排名:千里之外
    • 原创:42篇
    • 转载:18篇
    • 译文:0篇
    • 评论:0条
    文章分类