zoukankan      html  css  js  c++  java
  • Java 上传图片时按比例压缩图片

    一、在文件上传时的代码,判断是否需要进行压缩

    if(!filename.endsWith(".xlsx")&&!filename.endsWith(".xls")){
    String p="Http://"+domain+":90"+SERVER_IMG_COURSE_CHOOSE_PATH+"/"+filename;
    URL url = new URL(p);
    /** 对服务器上的临时文件进行处理 */
    Image srcFile = ImageIO.read(url);
    int w=srcFile.getWidth(null);
    int h=srcFile.getWidth(null);
    if(w>320||h>180){
    InputStream id=ImageZipUtil.zipWidthHeightImageFile(srcFile, filename,p, 320, 180, 0.8f);

    if (!ftp.storeFile(new String(filename.getBytes("utf-8"),"iso-8859-1"), id)) {
    return result;
    }
    id.close();
    }
    }

    二、压缩方法

    public static InputStream zipWidthHeightImageFile(Image im, String filename,String str,int width, int height, float quality) {

    Image srcFile = null;
    BufferedImage buffImg = null;
    InputStream is=null;
    try {
    URL url = new URL(str);
    /** 对服务器上的临时文件进行处理 */
    srcFile = ImageIO.read(url);

    // String srcImgPath = newFile.getAbsoluteFile().toString();
    // System.out.println(srcImgPath);
    String subfix = "jpg";
    subfix = filename.substring(filename.lastIndexOf(".") + 1, filename.length());

    if (subfix.equals("png")) {
    buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    } else {
    buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    }

    Graphics2D graphics = buffImg.createGraphics();
    graphics.setBackground(new Color(255, 255, 255));
    graphics.setColor(new Color(255, 255, 255));
    graphics.fillRect(0, 0, width, height);
    graphics.drawImage(srcFile.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    // ImageIO.write(image, "gif", os);
    ImageIO.write(buffImg, subfix, os);
    is = new ByteArrayInputStream(os.toByteArray());

    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    if (srcFile != null) {
    srcFile.flush();
    }
    if (buffImg != null) {
    buffImg.flush();
    }

    }
    return is;
    }

  • 相关阅读:
    kali网卡配置文件
    haproxy配置文件详解和ACL功能
    Linux查询端口是否被占用的四种方法
    为Linux配置常用源:epel和IUS
    高可用之KeepAlived(2):keepalived+lvs
    高可用之KeepAlived(一):基本概念和配置文件分析
    应用负载均衡之LVS(四):详细剖析VS/NAT和VS/DR模式
    应用负载均衡之LVS(二):VS_TUN和VS_DR的arp问题
    wget命令的几个常用选项和示例
    应用负载均衡之LVS(一):基本概念和三种模式
  • 原文地址:https://www.cnblogs.com/hm1990hpu/p/8349536.html
Copyright © 2011-2022 走看看