java 图片缩放、裁剪。

1、缩放图片(源图片大小按多个尺寸压缩)

压缩规格: 1、实际图宽 / 图宽、实际图高 / 图高,取最小比值;
                     2、最小比值大于1,按最小比值进行缩放;
                     3、最小比值小于1,不变化。

2、裁剪图片(压缩图片按指定尺寸进行裁剪)

裁剪规则:1、裁剪点x,y;x为宽、y为高
    2、裁剪点计算:x = (缩放图片宽-图宽)/  2
                                                  y = (缩放图片高-图高)/  2

package com.ninepoint.babystar.test.action;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import org.jfree.chart.plot.Zoomable;
/**
 * 图片缩放、切割
 * 1、图宽:实际图宽=图宽比
 *    图高:实际图稿=图高比
 * 2、图宽比与图高比,取最小值
 * 3、最小比值是否大于1
 *    3.1、大于1     成比例缩放
 *    3.2、小于1     取最小的宽
 * 4、切割 以中间段切割(图片格式都是PNG)
 */
/**
 * 
 * @Description  图片缩放、切割
 * @author nier_ni
 * @date 2015-9-17 下午07:47:15 
 * @version
 */
public class ImgZoomAndCut {
private static List<String> tables = null;
	static{
		tables  = new ArrayList<String>();
		try{
		   InputStream in = KeyWordFilter.class.getClassLoader().getResourceAsStream("picture.properties.txt");
		   Properties pro = new Properties();
		   pro.load(in);
		   Enumeration enu = pro.propertyNames(); 
		   while(enu.hasMoreElements()){
			   String table = Pattern.compile(new String(((String)enu.nextElement()).getBytes("ISO-8859-1"), "UTF-8")).toString();
			   tables.add(table);
		   }
		}catch(IOException ioEx){
			ioEx.printStackTrace();
		}
	}
	/**
     * 
     * @Description 图片按多个尺寸压缩切割
     */
    public static void PictureBySizeCompressionCutting(String picPath){
    	for(int i = 0; i < tables.size(); i++){
    		System.out.println(tables.get(i));
    		String[] strs = tables.get(i).split(",");
    		imgZoomAndCutDemo(picPath,Integer.parseInt(strs[0]),Integer.parseInt(strs[1]));
    	}
    }
	/**
	 * 
	 * @Description 图片成比例缩放
	 * @param srcImageFile 源图像文件地址
	 * @param result 缩放后的图像地址
	 * @param scale 缩放比例
	 * @param flag 缩放选择:true 放大; false 缩小;
	 */
	private static int x = 0;
	private static int y = 0;
	public static void imgZoom(String srcImageFile, String result, int scale, boolean flag){
	  try {
            BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件
            int width = src.getWidth(); // 得到源图宽
            int height = src.getHeight(); // 得到源图长
            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, "PNG", new File(result));// 输出到文件流
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
	 /**
     * @Description 图像切割(按指定起点坐标和宽高切割)
     * @param srcImageFile 源图像地址
     * @param result 切片后的图像地址
     * @param x 目标切片起点坐标X
     * @param y 目标切片起点坐标Y
     * @param width 目标切片宽度
     * @param height 目标切片高度
     */
    public final static void ImgCut(String srcImageFile, String result,
            int x, int y, int width, int height) {
        try {
            // 读取源图像
        	System.out.println("切割图片大小Width:" + width + ",Height:" + height);
            BufferedImage bi = ImageIO.read(new File(srcImageFile));
            int srcWidth = bi.getHeight(); // 源图宽度
            int srcHeight = bi.getWidth(); // 源图高度
            if (srcWidth > 0 && srcHeight > 0) {
                Image image = bi.getScaledInstance(srcWidth, srcHeight,
                        Image.SCALE_DEFAULT);
                // 四个参数分别为图像起点坐标和宽高
                // 即: CropImageFilter(int x,int y,int width,int height)
                ImageFilter cropFilter = new CropImageFilter(x, y, width, height);
                Image img = Toolkit.getDefaultToolkit().createImage(
                        new FilteredImageSource(image.getSource(),
                                cropFilter));
                BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics g = tag.getGraphics();
                g.drawImage(img, 0, 0, width, height, null); // 绘制切割后的图
                g.dispose();
                // 输出为文件
                ImageIO.write(tag, "PNG", new File(result));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	/**
	 * 
	 * @Description  计算图片缩放比例
	 * @param srcImageFile 源图像地址
	 * @param width 实际图片宽
	 * @param height 实际图片高
	 * @return
	 */
	public static int scaling(String srcImageFile,int width, int height){
		int smallValue = 0;
		try {
            // 读取源图像
            BufferedImage bi = ImageIO.read(new File(srcImageFile));
            int srcWidth = bi.getHeight(); // 源图宽度
            int srcHeight = bi.getWidth(); // 源图高度
            int scaleWidth = srcWidth/width;
            int scaleHeight = srcHeight/height;
            //获取比例最小值
            smallValue = intCompare(scaleWidth,scaleHeight);
		} catch (Exception e) {
            e.printStackTrace();
        }
		return smallValue;
	}
	/**
	 * @Description 两个数字取最小值(int类型)
	 * @param scaleWidth 宽比值
	 * @param scaleHeight 高比值
	 * @return
	 */
	public static int intCompare(int scaleWidth, int scaleHeight){
		int result = 0;
	    if (scaleWidth > scaleHeight) {  
	        result = scaleHeight;  
	    }else if (scaleWidth < scaleHeight) {  
	        result = scaleWidth;  
	    }else if (scaleWidth == scaleHeight) {  
	        result = scaleWidth;  
	    }
		return result;
	}
	/**
	 * 
	 * @Description 计算图片的切割点
	 * @param zoomImageFile 缩放图片地址
	 * @param width 实际图片宽
	 * @param height 实际图片高
	 */
	public static void cutPosition(int cutType,String zoomImageFile,double width, double height){
		try {
            // 读取源图像
			System.out.println("读取源图像:" + zoomImageFile);
            BufferedImage bi = ImageIO.read(new File(zoomImageFile));
            double srcWidth = bi.getHeight(); // 源图宽度
            double srcHeight = bi.getWidth(); // 源图高度
            System.out.println("源图宽度:"+srcWidth +",源图高度:" + srcHeight + "。");
            switch (cutType) {
			case 1:
				if(srcWidth > width){
	            	x = (int)(srcWidth/2 - width/2);
	            }
	            if(srcHeight > height){
	            	y = (int)(srcHeight/2 - height/2);
	            }
				break;
			case 0:
				if(srcWidth == width){
					x = 0;
				}else{
					x = (int)srcWidth/2;
				}
				if(srcHeight == height){
					y = 0;
				}else{
					y = (int)srcHeight/2;
				}
				break;
			default:
				if(srcWidth > width){
	            	x = (int)(srcWidth/2 - (width*cutType)/2);
	            }
	            if(srcHeight > height){
	            	y = (int)(srcHeight/2 - (height*cutType)/2);
	            }
				break;
			}
            System.out.println("切割:" + x +",切割y:" + y + "。");
		} catch (Exception e) {
            e.printStackTrace();
        }
	}
	/**
	 * 
	 * @Description 获得缩放图片的地址
	 * @param srcImageFile 源图像文件地址
	 * @param scale 缩放比例
	 * @return
	 */
	public static String zoomFileName(String srcImageFile,int scale){
		StringBuffer filePath = new StringBuffer();
		String strs[] = filePathSplit(srcImageFile);
		if(strs.length > 1){
			filePath.append(strs[0]);
			filePath.append("\\");
			filePath.append(strs[1]);
			filePath.append("_");
			filePath.append(scale);
			filePath.append(".png");
		}
		return filePath.toString();
	}
	/**
	 * 
	 * @Description 获取切割图片的地址
	 * @param zoomImageFile 缩放图片地址
	 * @param width 实际图片宽
	 * @param height 实际图片高
	 * @return
	 */
	public static String cutFileName(int isZoom,String zoomImageFile,int width, int height){
		StringBuffer filePath = new StringBuffer();
		String strs[] = filePathSplit(zoomImageFile);
		if(strs.length > 1){
			filePath.append(strs[0]);
			filePath.append("\\");
			if(isZoom == 1){
				filePath.append(strs[1].substring(0, strs[1].lastIndexOf("_")));
			}else{
				filePath.append(strs[1]);
			}
			filePath.append("_");
			filePath.append(width);
			filePath.append("_");
			filePath.append(height);
			filePath.append(".png");
		}
		return filePath.toString();
	}
	/**
	 * 
	 * @Description 分离路径与文件名(文件名不包含扩展名)
	 * @param filePath 文件全路径
	 * @return
	 */
	public static String[] filePathSplit(String filePath){
		//System.out.println("路径:" + filePath);
		String strs[] = new String[2];
		strs[0] = filePath.substring(0, filePath.lastIndexOf("\\"));
		String fileName = filePath.substring(filePath.lastIndexOf("\\")+1);
		fileName = fileName.substring(0,fileName.lastIndexOf("."));
		strs[1] = fileName;
		return strs;
	}
	/**
	 * 
	 * @Description 先缩放后切割 
	 * @param srcImageFile 源图像文件地址
	 * @param width 实际图片宽
	 * @param height 实际图片高
	 */
	public static void imgZoomAndCutDemo(String srcImageFile,int width, int height){
		/**
		 * 1、图片缩放比例
		 * 2、图片缩放
		 * 3、切割点
		 * 4、图片切割
		 */
		try {
			int picWidth = width;
			int picHeight = height;
			int isZoom = 0;//是否压缩
			BufferedImage bi = ImageIO.read(new File(srcImageFile));
	        int srcWidth = bi.getHeight(); // 源图宽度
	        int srcHeight = bi.getWidth(); // 源图高度
			int scale = scaling(srcImageFile,width,height);
			String zoomFileName = srcImageFile;
			if(scale > 1){
				zoomFileName = zoomFileName(srcImageFile,scale);
				imgZoom(srcImageFile, zoomFileName, scale, false);
				isZoom = 1;
				cutPosition(1,zoomFileName,picWidth,picHeight);
			}else if(scale < 1){
				int length = intCompare(srcWidth,srcHeight);
				picWidth = length;
				picHeight = length;
				cutPosition(scale,zoomFileName,picWidth,picHeight);
			}else if(scale == 1){
				int length = intCompare(srcWidth,srcHeight);
				picWidth = length;
				picHeight = length;
				cutPosition(scale,zoomFileName,picWidth,picHeight);
			}
			String cutFileName = cutFileName(isZoom,zoomFileName, width, height);
			cutPic(zoomFileName, cutFileName, y, x, picWidth, picHeight);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 
	 * @Description 先切割后缩放
	 * @author Administrator
	 * @param srcImageFile
	 * @param width
	 * @param height
	 */
	/**public static void imgCutAndZoomDemo(String srcImageFile,int width, int height){
		/**
		 * 1、切割点
		 * 2、图片切割
		 * 3、图片缩放比例s
		 * 4、图片缩放
		int scale = scaling(srcImageFile,width,height);
		System.out.println("图片缩放:" + scale + "倍。");
		String cutFileName = cutFileName(1,srcImageFile, width, height);
		//获取切割点
		cutPosition(scale,srcImageFile,width,height);
		System.out.println("切割点:" + x + "," + y + "。");
		ImgCut(srcImageFile, cutFileName, y, x, width*scale, height*scale);
		String zoomFileName = zoomFileName(cutFileName,scale);
		imgZoom(cutFileName, zoomFileName, scale, false);
	}*/
	public static void main(String[] args) {
		//imgZoom("D:\\photo\\ImgZoom\\grass.jpg","D:\\photo\\ImgZoom\\grass_2.png",2,false);
		//ImgCut("D:\\photo\\ImgZoom\\grass_2.png","D:\\photo\\ImgZoom\\grass_3.png",0,0,200,200);
		imgZoomAndCutDemo("D:\\photo\\ImgZoom\\grass.jpg",200,200);
		//imgZoomAndCutDemo("D:\\photo\\ImgZoom\\small.jpg",500,500);
		//imgZoomAndCutDemo("D:\\photo\\ImgZoom\\small.jpg",200,200);
		//imgZoomAndCutDemo("D:\\photo\\ImgZoom\\grass_4.png",213,213);
		//imgZoomAndCutDemo("D:\\photo\\ImgZoom\\height.png",327,327);
		//imgCutAndZoomDemo("D:\\photo\\ImgZoom\\CutAndZoom\\grass.jpg",200,200);
		//ImgCut("D:\\photo\\ImgZoom\\grass.jpg","D:\\photo\\ImgZoom\\grass1.jpg",0,0,200,200);
		//cutPic("D:\\photo\\ImgZoom\\grass.jpg","D:\\photo\\ImgZoom\\grass2.jpg",0,0,200,200);
	}
	 /** 
     * @param srcFile源文件 
     * @param outFile输出文件 
     * @param x坐标 
     * @param y坐标 
     * @param width宽度 
     * @param height高度 
     * @return 
     * @作者 王建明 
     * @创建日期 2012-8-2 
     * @创建时间 下午02:05:03 
     * @描述 —— 裁剪图片 
     */  
    public static boolean cutPic(String srcFile, String outFile, int x, int y,  
            int width, int height) {  
        FileInputStream is = null;  
        ImageInputStream iis = null;  
        try {  
            // 如果源图片不存在  
            if (!new File(srcFile).exists()) {  
                return false;  
            }  
  
            // 读取图片文件  
            is = new FileInputStream(srcFile);  
  
            // 获取文件格式  
            String ext = srcFile.substring(srcFile.lastIndexOf(".") + 1);  
  
            // ImageReader声称能够解码指定格式  
            Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(ext);  
            ImageReader reader = it.next();  
  
            // 获取图片流  
            iis = ImageIO.createImageInputStream(is);  
  
            // 输入源中的图像将只按顺序读取  
            reader.setInput(iis, true);  
  
            // 描述如何对流进行解码  
            ImageReadParam param = reader.getDefaultReadParam();  
  
            // 图片裁剪区域  
            Rectangle rect = new Rectangle(x, y, width, height);  
  
            // 提供一个 BufferedImage,将其用作解码像素数据的目标  
            param.setSourceRegion(rect);  
  
            // 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象  
            BufferedImage bi = reader.read(0, param);  
  
            // 保存新图片  
            File tempOutFile = new File(outFile);  
            if (!tempOutFile.exists()) {  
                tempOutFile.mkdirs();  
            }  
            ImageIO.write(bi, ext, new File(outFile));  
            return true;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        } finally {  
            try {  
                if (is != null) {  
                    is.close();  
                }  
                if (iis != null) {  
                    iis.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
                return false;  
            }  
        }  
    }  
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值