服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - java项目实现图片等比缩放

java项目实现图片等比缩放

2022-11-20 14:41xiegongmiao Java教程

这篇文章主要为大家详细介绍了java项目实现图片等比缩放,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了java项目实现图片等比缩放的具体代码,供大家参考,具体内容如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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()

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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>());
    }
}

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

原文链接:https://blog.csdn.net/xiegongmiao/article/details/78624317

延伸 · 阅读

精彩推荐