利用java怎么对图片进行压缩与缩放

发布时间:2020-11-27 17:22:51 作者:Leah
来源:亿速云 阅读:120

这篇文章将为大家详细讲解有关利用java怎么对图片进行压缩与缩放,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

压缩

public static boolean compress(String src,String to, float quality) {
    boolean rs = true;

    // Build param
    JPEGEncodeParam param = null;

    // Build encoder
    File destination = new File(to);
    FileOutputStream os = null;
    try {
      BufferedImage image = ImageIO.read(new File(src));
      param = JPEGCodec.getDefaultJPEGEncodeParam(image);
      param.setQuality(quality, false);

      os = FileUtils.openOutputStream(destination);
      JPEGImageEncoder encoder;
      if (param != null) {
        encoder = JPEGCodec.createJPEGEncoder(os, param);
      } else {
        return false;
      }
      encoder.encode(image);
    } catch(Exception e){
      e.printStackTrace();
      rs = false;
    }finally {
      IOUtils.closeQuietly(os);
    }
    return rs;
  }

缩放

public static boolean resize(String src,String to,int newWidth,int newHeight) {
    try {
      File srcFile = new File(src);
      File toFile = new File(to);
      BufferedImage img = ImageIO.read(srcFile);
      int w = img.getWidth();
      int h = img.getHeight();
      BufferedImage dimg = new BufferedImage(newWidth, newHeight, img.getType());
      Graphics2D g = dimg.createGraphics();
      g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
      g.drawImage(img, 0, 0, newWidth, newHeight, 0, 0, w, h, null);
      g.dispose();
      ImageIO.write(dimg, "jpg", toFile);
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
    return true;
  }

关于利用java怎么对图片进行压缩与缩放就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. Java 对图片缩放处理
  2. 利用PHP怎么对图片进行等比例缩放

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java ava

上一篇:listener监听器在Java中的作用有哪些

下一篇:Java中如何对日期时间进行格式化

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》