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;
    }

  • 相关阅读:
    数据仓库的直白概述
    Google准实时数据仓库Mesa(一)
    活动预告丨易盾CTO朱浩齐将出席2018 AIIA大会,分享《人工智能在内容安全的应用实践》
    3招搞定APP注册作弊
    【0门槛】PR稿的自我修养
    Hive中文注释乱码解决方案(2)
    Hive中文注释乱码解决方案
    网易考拉Android客户端网络模块设计
    有运气摇号来不及挑选?网易有数帮你科学选房
    selenium下拉框踩坑埋坑
  • 原文地址:https://www.cnblogs.com/hm1990hpu/p/8349536.html
Copyright © 2011-2022 走看看