java 图片压缩和resize java对图片进行压缩和resize缩放的方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

java 图片压缩和resize java对图片进行压缩和resize缩放的方法

xixicat   2021-03-23 我要评论
想了解java对图片进行压缩和resize缩放的方法的相关内容吗,xixicat在本文为您仔细讲解java 图片压缩和resize的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:java,图片压缩,java,图片,resize,下面大家一起来学习吧。


这里展示一下如何对图片进行压缩和resize。分享给大家,具体如下:

压缩

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

resize

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

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们