java 图片image工具类,ImageUtil.java

1.java 图片image工具类,ImageUtil.java

package com.broadway.numpeople.utils;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
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.FileOutputStream;
import java.util.Date;
import javax.imageio.ImageIO;


public class ImageUtil {
	/**
	 * 裁剪PNG图片工具类
	 * 
	 * @param fromFile
	 *            源文件
	 * @param toFile
	 *            裁剪后的文件
	 * @param outputWidth
	 *            裁剪宽度
	 * @param outputHeight
	 *            裁剪高度
	 * @param proportion
	 *            是否是等比缩放
	 */
	public static void resizePng(File fromFile, File toFile, int outputWidth, int outputHeight,
			boolean proportion) {
		try {
			BufferedImage bi2 = ImageIO.read(fromFile);
			int newWidth;
			int newHeight;
			// 判断是否是等比缩放
			if (proportion) {
				// 为等比缩放计算输出的图片宽度及高度
				double rate1 = ((double) bi2.getWidth(null)) / (double) outputWidth + 0.1;
				double rate2 = ((double) bi2.getHeight(null)) / (double) outputHeight + 0.1;
				// 根据缩放比率大的进行缩放控制
				double rate = rate1 < rate2 ? rate1 : rate2;
				newWidth = (int) (((double) bi2.getWidth(null)) / rate);
				newHeight = (int) (((double) bi2.getHeight(null)) / rate);
			} else {
				newWidth = outputWidth; // 输出的图片宽度
				newHeight = outputHeight; // 输出的图片高度
			}
			BufferedImage to = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
			Graphics2D g2d = to.createGraphics();
			to = g2d.getDeviceConfiguration().createCompatibleImage(newWidth, newHeight,Transparency.TRANSLUCENT);
			g2d.dispose();
			g2d = to.createGraphics();
			@SuppressWarnings("static-access")
			Image from = bi2.getScaledInstance(newWidth, newHeight, bi2.SCALE_AREA_AVERAGING);
			g2d.drawImage(from, 0, 0, null);
			g2d.dispose();
			
			ImageIO.write(to, "png", toFile);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//图片切割  四个参数分别为图像起点坐标和宽高
	public static BufferedImage cutImage(BufferedImage bi, int start_width,int start_height,int outputWidth, int outputHeight){
		try{
			// 源图宽度
			int srcWidth = bi.getWidth();
			// 源图高度
			int srcHeight = bi.getHeight();
			
			int destHeight = outputHeight;
			int destWidth = outputWidth;
			
			Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);
			
			Image img;
			ImageFilter cropFilter;
			// 四个参数分别为图像起点坐标和宽高
			cropFilter = new CropImageFilter(start_width, start_height,destWidth, destHeight);
			img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));

			BufferedImage tag = new BufferedImage(destWidth, destHeight,BufferedImage.TYPE_INT_RGB);
			
			
			Graphics2D g2d = tag.createGraphics();
			tag = g2d.getDeviceConfiguration().createCompatibleImage(destWidth, destHeight,Transparency.TRANSLUCENT);
			g2d.dispose();
			g2d = tag.createGraphics();
//			@SuppressWarnings("static-access")
//			Image from = bi.getScaledInstance(destWidth, destHeight, bi.SCALE_AREA_AVERAGING);
			g2d.drawImage(img, 0, 0, null);
			g2d.dispose();
			
//			Graphics g = tag.getGraphics();
//			g.drawImage(img, 0, 0, null); // 绘制缩小后的图
//			g.dispose();
			
			return tag;
			
		}catch (Exception e){
			e.printStackTrace();
		}
		return null;

	}
 
	/**按照参数的宽高,拉伸图片
	 * 
	 * fromFile:源图片
	 * saveFile:保存的新图片
	 * 
	 * */
	public static void ratioByWidthHeightImage(File fromFile, File saveFile, int width_bg, int height_bg) {
		try {
			
			BufferedImage image = ImageIO.read(fromFile);
			BufferedImage imageNew = new BufferedImage(width_bg,height_bg,BufferedImage.TYPE_INT_RGB);
			
	        imageNew.getGraphics().drawImage(image.getScaledInstance(width_bg, height_bg, Image.SCALE_SMOOTH), 0, 0, null); // 绘制缩小后的图
	       
	        ImageIO.write(imageNew, "PNG", saveFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

	/**
     * 旋转图片
     * @param image
     * @param degree:旋转角度
     * @param bgcolor:背景颜色 可为null
     * @return
     */
    public static BufferedImage rotateImg(BufferedImage image, int degree, Color bgcolor) {
    	BufferedImage return_bi = null;
    	try {
	        int iw = image.getWidth();//原始图象的宽度
	        int ih = image.getHeight();//原始图象的高度
	        int w = 0;
	        int h = 0;
	        int x = 0;
	        int y = 0;
	        degree = degree % 360;
	        if (degree < 0)
	            degree = 360 + degree;//将角度转换到0-360度之间
	        double ang = Math.toRadians(degree);//将角度转为弧度
	
	        /**
	         *确定旋转后的图象的高度和宽度
	         */
	
	        if (degree == 180 || degree == 0 || degree == 360) {
	            w = iw;
	            h = ih;
	        } else if (degree == 90 || degree == 270) {
	            w = ih;
	            h = iw;
	        } else {
	            int d = iw + ih;
	            w = (int) (d * Math.abs(Math.cos(ang)));
	            h = (int) (d * Math.abs(Math.sin(ang)));
	        }
	
	        x = (w / 2) - (iw / 2);//确定原点坐标
	        y = (h / 2) - (ih / 2);
	        BufferedImage rotatedImage = new BufferedImage(w, h, image.getType());
	        Graphics2D gs = (Graphics2D) rotatedImage.getGraphics();
	        if (bgcolor == null) {
	            rotatedImage = gs.getDeviceConfiguration().createCompatibleImage(w, h, Transparency.TRANSLUCENT);
	        } else {
	            gs.setColor(bgcolor);
	            gs.fillRect(0, 0, w, h);//以给定颜色绘制旋转后图片的背景
	        }
	
	        AffineTransform at = new AffineTransform();
	        at.rotate(ang, w / 2, h / 2);//旋转图象
	        at.translate(x, y);
	        AffineTransformOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
	        op.filter(image, rotatedImage);
	        
	        return_bi = rotatedImage;
//	        image = rotatedImage;
//	
//	        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
//	        ImageOutputStream imageOut = ImageIO.createImageOutputStream(byteOut);
//	        ImageIO.write(image, "png", imageOut);
//	        return new ByteArrayInputStream(byteOut.toByteArray());
    	} catch (Exception e) {
			e.printStackTrace();
		}   
    	return return_bi;
    }


	/**
     * 设置背景色
     * @param image
     * @param color:背景颜色 可为null
     * @return
     */
    public static BufferedImage setBgColor(BufferedImage srcImage, Color color) {
    	BufferedImage return_bi = null;
    	try {
	        int w = srcImage.getWidth();//原始图象的宽度
	        int h = srcImage.getHeight();//原始图象的高度
	       
	        return_bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
	        Graphics2D gs = (Graphics2D) return_bi.getGraphics();
	       
	        // 设置背景颜色
//	        gs.setBackground(Color.WHITE);
	        gs.setBackground(color);
	        gs.clearRect(0, 0, w, h);
	        
	        // 设置图片居中显示
	        gs.drawImage(srcImage, 0, 0, null);
	        gs.dispose();
            
	        
    	} catch (Exception e) {
			e.printStackTrace();
		}   
    	return return_bi;
    }

    /**合并图片 - 水平合并
	 * 注意:水平合并时,需要注意两张图片的高度要一致
	 * bi:源图片
	 * bi2:源图片2
	 * */
	public static BufferedImage mergeImage_x(BufferedImage bi, BufferedImage bi2) {
		try {
			
			// 源图宽/高
			int w1 = bi.getWidth();
			int h1 = bi.getHeight();
			
			// 源2图宽/高
			int w2 = bi2.getWidth();
//			int h2 = bi2.getHeight();
			
			int destWidth = w1 + w2;
			int destHeight = h1;
			
	        // 生成新图片
	        BufferedImage destImage = new BufferedImage(w1 + w2, h1, BufferedImage.TYPE_INT_RGB);
	        Graphics2D g2d = destImage.createGraphics();
	        destImage = g2d.getDeviceConfiguration().createCompatibleImage(destWidth, destHeight,Transparency.TRANSLUCENT);
			g2d.dispose();
			g2d = destImage.createGraphics();
			g2d.drawImage(bi, 0, 0, w1, h1, null);
			g2d.drawImage(bi2, w1, 0, w2, h1, null);
			g2d.dispose();
			
			
			return destImage;  
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bi;
	}
    
    /**合并图片 
	 * 
	 * bi:源图片
	 * bi2:源图片2
	 * bi2图片压bi的图片
	 * */
	public static BufferedImage mergeImage(BufferedImage bi, BufferedImage bi2) {
		try {
			
			// 源图宽度
			int w = bi.getWidth();
			// 源图高度
			int h = bi.getHeight();
			
			
			Graphics g = bi.getGraphics();
			g.drawImage(bi2, 0, 0, w, h, null);  
	        g.dispose();  
			
			  
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bi;
	}
	
	//文件的复制
	public static void imageCopy(String srcFile,String destFile){
		try {
			//创建文件输入流对象读取指定目录下的文件
			FileInputStream in=new FileInputStream(srcFile);
			//创建文件输出流对象读取指定目录下的文件
			FileOutputStream out=new FileOutputStream(destFile);
			
			byte[] buffer = new byte[1024]; 
			
			//定义一个int类型的变量length
			int length=0;
			//获取文件拷贝的时间
//				long beginTime=System.currentTimeMillis();
			//通过循环将读取到的文件字节信息写入到新文件
			while((length=in.read(buffer)) > 0) {
				out.write(buffer,0,length);
			}
//				//获取拷贝后的时间
//				long endTime=System.currentTimeMillis();
//				//输出拷贝花费的时间
//				System.out.println("花费时间为:"+(endTime-beginTime)+"毫秒");
			//关闭流
			in.close();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	


	
	/**
	 * 测试
	 */
	public static void main(String[] args) throws Exception {
		Date date = new Date();
//		File fromFile = new File("c:/1.png");
//		File toFile = new File("c:/2.png");
//		resizePng(fromFile, toFile, 100, 100, false);
		
		
		//旋转图片
//		File srcImage = new File("D:/2023/2023-03/test.png");
//		BufferedImage image = ImageIO.read(srcImage);
//		int degree = 90;//旋转角度
//	    BufferedImage rotateImg = rotateImg(image,degree, null);
//	    String result_file_name = "D:/2023/2023-03/test_2.png";
//	    // 输出为文件
//		ImageIO.write(rotateImg, "png", new File(result_file_name));
		
		//合并图片
//		File srcImage = new File("D:/2023/2023-03/test_merge1.png");
//		BufferedImage bi1 = ImageIO.read(srcImage);
//		File srcImage2 = new File("D:/2023/2023-03/test_merge2.png");
//		BufferedImage bi2 = ImageIO.read(srcImage2);
//		BufferedImage result_bi = mergeImage( bi1, bi2);
//		String result_file_name = "D:/2023/2023-03/test_merge_result.png";
//	    // 输出为文件
//		ImageIO.write(result_bi, "png", new File(result_file_name));
		
		
		//文件的复制
		//imageCopy("D:/2023/2023-03/test_merge1.png","D:/2023/2023-03/test_merge1_copy.png");
		
		//设置背景色
		File srcImage = new File("D:/2023/2023-03/test.png");
		BufferedImage bi1 = ImageIO.read(srcImage);
		BufferedImage result_bi = setBgColor(bi1, Color.green);
		String result_file_name = "D:/2023/2023-03/test_bg_result.png";
	    // 输出为文件
		ImageIO.write(result_bi, "png", new File(result_file_name));
		
		System.out.println("花费:"+(new Date().getTime() - date.getTime()));
		
	}
}




  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雄哥007

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值