java项目实例图片等比缩放简化

本文主要介绍了如何使用Java进行图片的等比缩放操作,通过创建ImageTest类并在main方法中实现缩放功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java图片等比缩放

package common;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;

public class ImageCompressionTask implements Runnable{
      
	private InputStream is;
	private String fileName;
	private int width;
	private int height;

	/**
	 * 初始化参数
	 * @param is 图片输入流
	 * @param file  图片
	 * @param fileName  图片名称
	 * @param width   高
	 * @param height  宽
	 */
	public ImageCompressionTask(InputStream is,String fileName,int width,int height) {
		this.is=is;
		this.fileName=fileName;
		this.width=width;
		this.height=height;		
	}
	
	
	
	public void run() {
		// TODO Auto-generated method stub
		try{
			this.compressPic();
		}catch(Exception e){
			System.out.println("文件压缩失败"+e);
		}
		
	}
	
	private String compressPic() throws Exception{
		String path = "E:\\xie\\";//新图片存放路径
		String urlPath =  path + fileName;
		BufferedImage buffImage;
		FileOutputStream output=null;
		BufferedImage compressPic=null;
		try {
			
			String imagetype = "";
			if(fileName.lastIndexOf(".") != -1){
				imagetype = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
			}
			
			imagetype = imagetype.toLowerCase(); //文件后缀名
			output=new FileOutputStream(urlPath);
			buffImage=ImageIO.read(is);
			//图片缩放
			compressPic=compressPicMin(buffImage,width,height);
			//输出图片
			ImageIO.write(compressPic, imagetype, output);
		} finally {
			if(output!=null){
			   try{
			      output.close();
			   }catch(IOException e){
				   e.getStackTrace();
			   }
			}
			if(is!=null){
			   is.close();
			}
		}
		return fileName;
		
	}

    /**
     * 图片等比缩放
     *@param image 图片输入缓存流
     *@param outputWidth 图片压缩到的宽
     *@param outputHeight 图片压缩到的高
     *@return BufferedImage
     * */
	private BufferedImage compressPicMin(BufferedImage image,
	int outputWidth, int outputHeight) {
		// TODO Auto-generated method stub
		if(image==null){
			return null;
		}
		
		//如果图片本身的宽和高均小于要压缩到的宽和高,则不压缩直接返回
		if(outputWidth>image.getWidth(null)&&outputHeight>image.getHeight(null)){
			return image;
		}
		
		int newWidth;
		int newHeight;
	    //宽和高等比缩放的率
		double rate1=(double)image.getWidth(null)/(double)outputWidth;
		double rate2=(double)image.getHeight(null)/(double)outputHeight;
		//控制缩放大小
		double rate=rate1<rate2 ? rate1:rate2;
		newWidth=(int) (image.getWidth(null)/rate);
		newHeight=(int) (image.getHeight(null)/rate);
		
		BufferedImage newImage=new BufferedImage(newWidth, newHeight,BufferedImage.TYPE_INT_RGB);
		newImage.createGraphics().drawImage(image.getScaledInstance(newWidth, outputHeight, Image.SCALE_SMOOTH), 0, 0, null);

		return newImage;
	}
	
	public int getWidth() {
		return width;
	}


	public void setWidth(int width) {
		this.width = width;
	}


	public int getHeight() {
		return height;
	}


	public void setHeight(int height) {
		this.height = height;
	}


}

2.创建ImageTest写一个main()

package test1;


import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import common.ImageCompressionTask;


public class ImageTest {

	public static void main(String[] args){
		String imgName = System.currentTimeMillis() + "_" + ((int) (Math.random() * 900) + 100) + "." + "jpg";
		File f=new File("E:\\xie\\xxx.jpg");
		try {
			InputStream input = new FileInputStream(f);
			ImageCompressionTask r=new ImageCompressionTask(input, imgName, 520, 320);
			/*
			 * 方法一:
			 * 
			 Thread thread1 = new Thread(r);
			 thread1.start(); // 启动线程
			*/
			
			/*
			 * 方法二:使用ThreadPoolExecutor创建线程池,并不提倡我们直接使用ThreadPoolExecutor
			 * 
			 */
			/* ThreadPoolExecutor executor = new ThreadPoolExecutor(
			            5,  //核心池的大小(即线程池中的线程数目大于这个参数时,提交的任务会被放进任务缓存队列)
			            10, //线程池最大能容忍的线程数
			            200, //线程存活时间   
			            TimeUnit.MILLISECONDS, //参数keepAliveTime的时间单位
			            new ArrayBlockingQueue<Runnable>(5) //任务缓存队列,用来存放等待执行的任务
			 );
			executor.execute(r);*/
			/*
			 * 方法三:并不提倡我们直接使用ThreadPoolExecutor,而是使用Executors类中提供的几个静态方法来创建线程池
			 *  以下是三个静态方法
			 *  Executors.newCachedThreadPool();        //创建一个缓冲池,缓冲池容量大小为Integer.MAX_VALUE
                         *  Executors.newSingleThreadExecutor();   //创建容量为1的缓冲池
                         *  Executors.newFixedThreadPool(int);    //创建固定容量大小的缓冲池
			 */
			 newCachedThreadPool().execute(r);
			 //newSingleThreadExecutor().execute(r);
			 //newFixedThreadPool(10).execute(r);
			System.out.println("图片上传成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/*静态方法的具体实现
	 * Executors.newCachedThreadPool()
	 * 创建一个缓冲池,缓冲池容量大小为Integer.MAX_VALUE
	 */
	public static ExecutorService newCachedThreadPool() {
	    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
	                                  60L, TimeUnit.SECONDS,
	                                  new SynchronousQueue<Runnable>());
	}
	
	/*静态方法的具体实现
	 * Executors.newSingleThreadExecutor() 
	 * 创建容量为1的缓冲池
	 */
	public static ExecutorService newSingleThreadExecutor() {
	    return  new ThreadPoolExecutor(1, 1,
	                                0L, TimeUnit.MILLISECONDS,
	                                new LinkedBlockingQueue<Runnable>());
	}
	
	/*静态方法的具体实现
	 * Executors.newFixedThreadPool(int) 
	 * 创建固定容量大小的缓冲池
	 */
	public static ExecutorService newFixedThreadPool(int nThreads) {
	    return new ThreadPoolExecutor(nThreads, nThreads,
	                                  0L, TimeUnit.MILLISECONDS,
	                                  new LinkedBlockingQueue<Runnable>());
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值