广告
返回顶部
首页 > 资讯 > 后端开发 > Python >java实现上传图片尺寸修改和质量压缩
  • 180
分享到

java实现上传图片尺寸修改和质量压缩

2024-04-02 19:04:59 180人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

本文实例为大家分享了java实现上传图片尺寸修改和质量压缩的具体代码,供大家参考,具体内容如下 package com.zity.frame.util;     import co

本文实例为大家分享了java实现上传图片尺寸修改和质量压缩的具体代码,供大家参考,具体内容如下

package com.zity.frame.util;
 

 
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import net.sourceforge.pinyin4j.PinyinHelper;
 
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.MalfORMedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Random;
  
  
 public class CompressPic {
     private File file = null; // 文件对象
     private String inputDir; // 输入图路径
     private String outputDir; // 输出图路径
     private String inputFileName; // 输入图文件名
     private String outputFileName; // 输出图文件名
     private int outputWidth = 300; // 默认输出图片宽
     private int outputHeight = 150; // 默认输出图片高
     private boolean proportion = true; // 是否等比缩放标记(默认为等比缩放)
     public CompressPic() { // 初始化变量
         inputDir = "";    
         outputDir = "";    
         inputFileName = "";    
         outputFileName = "";    
         outputWidth = 300;    
         outputHeight = 150;    
     }    
     public void setInputDir(String inputDir) {    
         this.inputDir = inputDir;    
     }    
     public void setOutputDir(String outputDir) {    
         this.outputDir = outputDir;    
     }    
     public void setInputFileName(String inputFileName) {    
         this.inputFileName = inputFileName;   
     }    
     public void setOutputFileName(String outputFileName) {    
         this.outputFileName = outputFileName;    
     }    
     public void setOutputWidth(int outputWidth) {   
         this.outputWidth = outputWidth;    
     }    
     public void setOutputHeight(int outputHeight) {    
         this.outputHeight = outputHeight;    
     }    
     public void setWidthAndHeight(int width, int height) {    
         this.outputWidth = width;   
         this.outputHeight = height;    
     }    
        
         
     public long getPicSize(String path) {    
         file = new File(path);
         return file.length();
     }   
        
     
     public String compressPic() {    
         try {    
             //获得源文件    
             file = new File(inputDir + inputFileName);    
             if (!file.exists()) {    
                 return "";    
             }
             // 生成存储路径
             File outDir = new File(outputDir);
             if(!outDir.exists()){
                 outDir.mkdirs();
             }
             Image img = ImageIO.read(file);
             // 判断图片格式是否正确    
             if(img==null){
                 return "";
             }
             if (img.getWidth(null) == -1) {   
                 System.out.println(" can't read,retry!" + "<BR>");    
                 return "no";    
             } else {    
                 int newWidth; int newHeight;    
                 // 判断是否是等比缩放    
                 if (this.proportion == true) {    
                     // 为等比缩放计算输出的图片宽度及高度    
                     int w =img.getWidth(null);
                     int h = img.getHeight(null);
                     //如果图片的宽度小于等于250,并且高度小于等于183,图片原样输出
                     if(w<=300){
                         outputWidth=w;
                     }
                     if(h<=150){
                         outputHeight=h;
                     }
                     double rate1 = ((double) img.getWidth(null)) / (double) outputWidth;    
                     double rate2 = ((double) img.getHeight(null)) / (double) outputHeight;    
                     // 根据缩放比率大的进行缩放控制    
//                     double rate = rate1 > rate2 ? rate1 : rate2;
                     // 保证宽度为250px
                     double rate = rate1;
                     newWidth = (int) (((double) img.getWidth(null)) / rate);    
                     newHeight = (int) (((double) img.getHeight(null)) / rate2);    
                 } else {    
                     newWidth = outputWidth; // 输出的图片宽度    
                     newHeight = outputHeight; // 输出的图片高度    
                 }
                 
                 //重新设置高宽为图片真实高宽,上面的高宽是其他项目需要300*150的,我没得空删掉
                 newWidth = getImgWidth(file);
                 newHeight = getImgHeight(file);
                BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);
                   
                    
                tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);   
                FileOutputStream out = new FileOutputStream(outputDir + outputFileName);   
                // JPEGImageEncoder可适用于其他图片类型的转换    
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);    
                encoder.encode(tag);    
                out.close();    
             }    
         } catch (IOException ex) {    
             ex.printStackTrace();    
         }    
         return "ok";    
    }
    
    
    public String compressPic (String inputDir, String outputDir, String inputFileName, String outputFileName) {    
        // 输入图路径    
        this.inputDir = inputDir;    
        // 输出图路径    
        this.outputDir = outputDir;    
        // 输入图文件名    
        this.inputFileName = inputFileName;    
        // 输出图文件名   
        this.outputFileName = outputFileName;    
        return compressPic();    
    }    
    
    
    public String compressPic(String inputDir, String outputDir, String inputFileName, String outputFileName, int width, int height, boolean gp) {    
        // 输入图路径    
        this.inputDir = inputDir;    
        // 输出图路径    
        this.outputDir = outputDir;    
        // 输入图文件名    
        this.inputFileName = inputFileName;    
        // 输出图文件名    
        this.outputFileName = outputFileName;    
        // 设置图片长宽   
        setWidthAndHeight(width, height);    
        // 是否是等比缩放 标记    
        this.proportion = gp;    
        return compressPic();    
    }
    
    
    public String ImageCompression(String downloadUrl,String inputDir,String outDir){
        
        Random rnd = new Random();
        String picName = downloadUrl.substring(downloadUrl.lastIndexOf("/")+1);
        String extendName ="";
        String beforeName= "";
        
        if(picName.contains(".")){
             extendName = picName.substring(picName.indexOf("."));
             beforeName= picName.substring(0,picName.indexOf("."));
        }else{
             extendName = picName;
             beforeName= picName;
        }
        
        //随机数
        Integer r = rnd.nextInt(1000);
        beforeName = new CompressPic().getPinYinHeadChar(beforeName);
        long ts = System.currentTimeMillis();
        String outpicName=ts+beforeName+r+".jpg";
        outpicName = outpicName.replace("%", "");
        if(outpicName.contains("张栋杰总经理会见旭阳集团董事长杨雪岗")){
            outpicName="zdjzjlhjxyjtdszyxg.jpg";
        }
        
        if(HttpDownload(downloadUrl, inputDir, outpicName)){
            // 当前时间
            // String curTime = new Long(System.currentTimeMillis()).toString();
            this.compressPic(inputDir, outDir, outpicName, outpicName, 300, 150, true);
            return outpicName;
        }else {
            return null;
        }
    }
    
    
    public static boolean httpDownload(String httpUrl,String saveDir,String saveName){
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;
        URL url = null;  
        try {
            url = new URL(httpUrl);  
        } catch (MalformedURLException e1) {  
            e1.printStackTrace();
            return false;  
        }
        // 存储目录
        File outDir = new File(saveDir);
        if(!outDir.exists()){
            outDir.mkdirs();
        }
        try {
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream(saveDir+saveName);
            
            byte[] buffer = new byte[1204];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }
            fs.close();
            inStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
      
    public  String getPinYinHeadChar(String str) {  
        String convert = "";  
        for (int j = 0; j < str.length(); j++) {  
            char Word = str.charAt(j);  
            // 提取汉字的首字母  
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);  
            if (pinyinArray != null) {  
                convert += pinyinArray[0].charAt(0);  
            } else {  
                convert += word;  
            }  
        }  
        return convert;  
    }  
    public static void main(String[] arg) {
        CompressPic mypic = new CompressPic();
        mypic.compressPic("C:\\Users\\mazhaoxu\\Desktop\\", "C:\\Users\\mazhaoxu\\Desktop\\", "微信图片_20180712182800.png", "2019061818542824511111111111.png");
//        if(httpDownload("http://221.195.72.44:8122/NR/rdonlyres/B5071DE7-9652-44AF-9534-0EE0ED2DCA92/15177/resource_651768621.jpg", "D:\\data\\resource_651768621.jpg")){
//            int start = (int) System.currentTimeMillis();   // 开始时间
//            mypic.compressPic("D:\\data\\", "D:\\data\\", "resource_651768621.jpg", "r1"+start+".jpg", 250, 250, true);
//        }
//       String s=  mypic.getPinYinHeadChar("http://114.251.186.42:81/WEB-s/images/1447069462915xfydh1_fb_fb521.jpg");
//        mypic.ImageCompression("http://114.251.186.42:81/web-s/images/mobile/1447069462915xfydh1_fb_fb521.jpg","d:\\images\\", "d:\\images\\mobile\\");
//        mypic.compressPic("d:\\", "d:\\image\\mobile", "144921941137520151204fgw1747.jpg", "144921941137520151204fgw1747.jpg");
//        String s = "/image/dslfsjss/image/sisis /image";
//            System.out.println(s.replace("/image/", "/mobile/image/"));
    }
 
 
    
    public static int getImgWidth(File file) {
        InputStream is = null;
        BufferedImage src = null;
        int ret = -1;
        try {
            is = new FileInputStream(file);
            src = javax.imageio.ImageIO.read(is);
            ret = src.getWidth(null); // 得到源图宽
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    
    public static int getImgHeight(File file) {
        InputStream is = null;
        BufferedImage src = null;
        int ret = -1;
        try {
            is = new FileInputStream(file);
            src = javax.imageio.ImageIO.read(is);
            ret = src.getHeight(null); // 得到源图高
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }
 }  

这是我用的工具类,其中里面业务会用到pinyin4j的jar包,和图片压缩关系不大,可以去除,我是因为比较着急改完,就没动,如果不想改,需要引入pinyin4j的jar包。

Maven:

<!-- https://mvnrepository.com/artifact/com.belerweb/pinyin4j -->
        <dependency>
            <groupId>com.belerweb</groupId>
            <artifactId>pinyin4j</artifactId>
            <version>2.5.0</version>
</dependency>

可以自行用上面工具类里的main方法进行测试

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

--结束END--

本文标题: java实现上传图片尺寸修改和质量压缩

本文链接: https://www.lsjlt.com/news/146895.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • java实现上传图片尺寸修改和质量压缩
    本文实例为大家分享了java实现上传图片尺寸修改和质量压缩的具体代码,供大家参考,具体内容如下 package com.zity.frame.util;     import co...
    99+
    2022-11-13
  • Android图片压缩(质量压缩和尺寸压缩)
    在网上调查了图片压缩的方法并实装后,大致上可以认为有两类压缩:质量压缩(不改变图片的尺寸)和尺寸压缩(相当于是像素上的压缩);质量压缩一般可用于上传大图前的处理,这样就可以节省一定的流量,毕竟现在的手机拍照都能达到3M左右了,尺寸压缩一般可...
    99+
    2023-05-31
    android 图片压缩 roi
  • java 实现图片像素质量压缩与图片长宽缩放
    目录java 图片像素质量压缩与图片长宽缩放java 修改图片dpi(像素/大小)java 图片像素质量压缩与图片长宽缩放 今天找到的这个方法比以前项目用到的方法更好,这里记录下,方...
    99+
    2022-11-12
  • Java修改图片大小尺寸的简单实现
    目录方式一:使用Image.getScaledInstance测试方式二:使用Thumbnailator测试方式一:使用Image.getScaledInstance 使用jdk的a...
    99+
    2022-11-12
  • java实现上传图片并压缩图片大小功能
    Thumbnailator 是一个优秀的图片处理的Google开源Java类库。处理效果远比Java API的好。从API提供现有的图像文件和图像对象的类中简化了处理过程,两三行代码就能够从现有图片生成处理后的图片,且允许微调图片的生成方式...
    99+
    2023-05-31
    java 上传图片 压缩图片
  • Nodejs中怎么实现图片上传和压缩预览功能
    这篇文章给大家介绍Nodejs中怎么实现图片上传和压缩预览功能,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。1、引入基本配置const Koa = req...
    99+
    2022-10-19
  • vue使用element实现上传图片和修改图片功能
    目录前言一、应用场景1.上传图片并进行放大预览2.图片上传代码二、修改已经上传的图片,并展示到图片列表中1.效果展示(先展示原来的图片,再上传新图片,也可删除原来的图片)2.编辑代码...
    99+
    2022-11-13
  • vue如何使用element实现上传图片和修改图片功能
    本篇内容主要讲解“vue如何使用element实现上传图片和修改图片功能”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“vue如何使用element实现上传图片和修改图片功能”吧!一、应用场景1....
    99+
    2023-07-02
  • HTML5 和小程序如何实现拍照图片旋转、压缩和上传功能
    这篇文章给大家分享的是有关HTML5 和小程序如何实现拍照图片旋转、压缩和上传功能的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。最近接到一个“发表评论”的需求:用户输入评论并且可以拍照或从相册选择图片上传,即支持...
    99+
    2023-06-09
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作