java文件比例缩小放大

1首先添加修改图片宽度和高度的方法

public static void reduceImg(String imgsrc, int widthdist, int heightdist) {
  try {
   File srcfile = new File(imgsrc);
   if (!srcfile.exists()) {
    return;
   }

   // 载入图片文件
   Image src = javax.imageio.ImageIO.read(srcfile);
   int w0 = src.getWidth(null); // 得到源图宽
   int h0 = src.getHeight(null); // 得到源图长

   BufferedImage tag = new BufferedImage((int) widthdist,
     (int) heightdist, BufferedImage.TYPE_INT_RGB);

   // 保存文件
   // 绘制缩小后的图
   tag.getGraphics().drawImage(
     src.getScaledInstance(widthdist, heightdist,
       java.awt.Image.SCALE_SMOOTH), 0, 0, null);
   // tag.getGraphics().drawImage(src.getScaledInstance(widthdist,
   // heightdist, Image.SCALE_AREA_AVERAGING), 0, 0, null);

   // 标注水印
   // int x = widthdist/10*8; //水印位置(x,y)
   // int y = heightdist/10*8;
   // jpg_logo( tag , x , y );

   // 重命名并新建图片
   String oleName = imgsrc.substring(imgsrc.lastIndexOf(".") - 1,
     imgsrc.lastIndexOf("."));
   String newName = oleName + "v";
   String imgdist = imgsrc.replace(oleName, newName);

   // 输出到文件流
   FileOutputStream out = new FileOutputStream(imgdist);
   JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
   // 近JPEG编码
   encoder.encode(tag);
   out.close();

  } catch (IOException ex) {
   ex.printStackTrace();
  }
 }

2按比例去缩小图片

public void BLDeal(String srcName,int width,int height) throws IOException
 {
  if (srcName != null) {
   BufferedImage sourceImg = javax.imageio.ImageIO
     .read(new File(srcName));

   if (sourceImg.getWidth() < width && sourceImg.getHeight() < height) {
    int beishu = (300 / sourceImg.getWidth()) > (300 / sourceImg
      .getHeight())? 300 / sourceImg.getHeight()
      : 300 / sourceImg.getWidth();
    reduceImg(srcName, sourceImg.getWidth() * beishu, sourceImg
      .getHeight()
      * beishu);
   }
 

  }
 }

原文地址:https://www.cnblogs.com/liaomin416100569/p/9332011.html