欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-19 23:20:10
序 这里展示一下如何对图片进行压缩和resize。分享给大家,具体如下: 压缩 public static boolean compress(stri...


这里展示一下如何对图片进行压缩和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;
  }

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

上一篇:

下一篇: