java项目实现图片等比缩放

 更新时间:2022年04月22日 14:51:53   作者:xiegongmiao  
这篇文章主要为大家详细介绍了java项目实现图片等比缩放,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了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;
    }
 
 
}

创建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>());
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • JAVA设计模式零基础解析之单例模式的八种方式

    JAVA设计模式零基础解析之单例模式的八种方式

    设计模式(Design pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性
    2021-10-10
  • SpringBoot 2 统一异常处理过程解析

    SpringBoot 2 统一异常处理过程解析

    这篇文章主要介绍了SpringBoot 2 统一异常处理过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-09-09
  • SpringBoot JPA实现增删改查、分页、排序、事务操作等功能示例

    SpringBoot JPA实现增删改查、分页、排序、事务操作等功能示例

    本篇文章主要介绍了SpringBoot JPA实现增删改查、分页、排序、事务操作等功能示例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
    2017-03-03
  • Spring @CrossOrigin 注解原理实现

    Spring @CrossOrigin 注解原理实现

    这篇文章主要介绍了Spring @CrossOrigin 注解原理实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-07-07
  • SpringBoot中如何处理不同的类型的POST请求

    SpringBoot中如何处理不同的类型的POST请求

    在Web开发中,POST请求是非常常见的,用于向服务器提交数据,根据数据的编码方式,POST请求可以分为form-data、x-www-form-urlencoded和raw三种类型,本文将介绍这三种请求方式的区别,并展示如何在Spring Boot中编写代码来处理它们,需要的朋友可以参考下
    2024-08-08
  • java集合类源码分析之Set详解

    java集合类源码分析之Set详解

    下面小编就为大家带来一篇java集合类源码分析之Set详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • JavaEE线程安全定时器模式任务

    JavaEE线程安全定时器模式任务

    这篇文章主要介绍了JavaEE线程安全定时器模式任务,定时器模式像是一个闹钟定时,在一定时间之后被唤醒并执行某个之前设定好的任务,感兴趣的小伙伴可以参考一下
    2022-06-06
  • MyBatis源码解析之Transaction事务模块

    MyBatis源码解析之Transaction事务模块

    这篇文章主要介绍了MyBatis源码解析之Transaction事务模块,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-10-10
  • springMVC如何将controller中Model数据传递到jsp页面

    springMVC如何将controller中Model数据传递到jsp页面

    本篇文章主要介绍了springMVC如何将controller中Model数据传递到jsp页面,具有一定的参考价值,有兴趣的可以了解一下
    2017-07-07
  • springmvc下实现登录验证码功能示例

    springmvc下实现登录验证码功能示例

    本篇文章主要介绍了springmvc下实现登录验证码功能示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-02-02

最新评论