图片缩放收藏

package tool;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.struts.upload.FormFile;

public class ChangeImageSize {
	/**
	 * 缩放图像
	 * 
	 * @param file
	 *            源图像文件地址
	 * @param result
	 *            缩放后的图像地址
	 * @param scale
	 *            缩放比例
	 * @param flag
	 *            缩放选择:true 放大; false 缩小;
	 */
	public static void scale(String file, String result, int scale,
			boolean flag) {
		try {
			BufferedImage src = ImageIO.read(new File(file)); // 读入文件
			int width = src.getWidth(); // 得到源图宽
			int height = src.getHeight(); // 得到源图长
			if (width <= 300) {
				//如果是小图片 缩小2倍
				scale=1;
			}else if (width>300&&width<=1024) {
				//大图片时缩小6陪
				scale=4;
			}else if (width>1024) {
				scale=10;
			}
			if (flag) {
				// 放大
				width = width * scale;
				height = height * scale;
			} else {
				// 缩小
				width = width / scale;
				height = height / scale;
			}
			Image image = src.getScaledInstance(width, height,
					Image.SCALE_DEFAULT);
			BufferedImage tag = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
			Graphics g = tag.getGraphics();
			g.drawImage(image, 0, 0, null); // 绘制缩小后的图
			g.dispose();
			ImageIO.write(tag, "JPEG", new File(result));// 输出到文件流
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

你可能感兴趣的:(java,apache,struts)