转载自  java 程序实现对图片的压缩生成缩略图并可设定长宽、尺寸压缩率、图片质量

之前是在另一位高手的上传内容中学习到的,并将其代码根据我的需求进行了修改,参考位置:http://jiangpin1987.javaeye.com/blog/749690
参考代码:
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.awt.*;
import com.sun.image.codec.jpeg.*;
import java.awt.image.BufferedImage;  public class Img_Middle {  public void img_change(String url, String name) {  Tosmallerpic(url, new File(url + name), "_middle", name, 188, 165,  (float) 0.7);  Tosmallerpic(url, new File(url + name), "_small", name, 45, 45,  (float) 0.7);  Tosmallerpic(url, new File(url + name), "_smaller", name, 116, 100,  (float) 0.7);  }  /** * * * @param f 图片所在的文件夹路径 * @param filelist 图片路径 * *  * @param ext *            扩展名 * @param n *            图片名 * @param w *            目标宽 * * @param h *            目标高 * * @param per *            百分比 */  private static void Tosmallerpic(String f, File filelist, String ext,  String n, int w, int h, float per) {  Image src;  try {  src = javax.imageio.ImageIO.read(filelist);  // 构造Image对象  String img_midname = f + n.substring(0, n.indexOf(".")) + ext  + n.substring(n.indexOf("."));  int old_w = src.getWidth(null); // 得到源图宽  int old_h = src.getHeight(null);  int new_w = 0;  int new_h = 0; // 得到源图长  double w2 = (old_w * 1.00) / (w * 1.00);  double h2 = (old_h * 1.00) / (h * 1.00);  // 图片跟据长宽留白,成一个正方形图。  BufferedImage oldpic;  if (old_w > old_h) {  oldpic = new BufferedImage(old_w, old_w,  BufferedImage.TYPE_INT_RGB);  } else {  if (old_w < old_h) {  oldpic = new BufferedImage(old_h, old_h,  BufferedImage.TYPE_INT_RGB);  } else {  oldpic = new BufferedImage(old_w, old_h,  BufferedImage.TYPE_INT_RGB);  }  }  Graphics2D g = oldpic.createGraphics();  g.setColor(Color.white);  if (old_w > old_h) {  g.fillRect(0, 0, old_w, old_w);  g.drawImage(src, 0, (old_w - old_h) / 2, old_w, old_h,  Color.white, null);  } else {  if (old_w < old_h) {  g.fillRect(0, 0, old_h, old_h);  g.drawImage(src, (old_h - old_w) / 2, 0, old_w, old_h,  Color.white, null);  } else {  // g.fillRect(0,0,old_h,old_h);  g.drawImage(src.getScaledInstance(old_w, old_h,  Image.SCALE_SMOOTH), 0, 0, null);  }  }  g.dispose();  src = oldpic;  // 图片调整为方形结束  if (old_w > w)  new_w = (int) Math.round(old_w / w2);  else  new_w = old_w;  if (old_h > h)  new_h = (int) Math.round(old_h / h2);// 计算新图长宽  else  new_h = old_h;  BufferedImage tag = new BufferedImage(new_w, new_h,  BufferedImage.TYPE_INT_RGB);  // tag.getGraphics().drawImage(src,0,0,new_w,new_h,null);  // 绘制缩小后的图  tag.getGraphics().drawImage(  src.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH), 0,  0, null);  FileOutputStream newimage = new FileOutputStream(img_midname); // 输出到文件流  JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);  JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);  /* 压缩质量 */  jep.setQuality(per, true);  encoder.encode(tag, jep);  // encoder.encode(tag);  // 近JPEG编码  newimage.close();  } catch (IOException ex) {  Logger.getLogger(Img_Middle.class.getName()).log(Level.SEVERE,  null, ex);  }  }  public static void main(String args[]){        //String n="0e5465fc-025a-458d-8383-e9ced0c1e728.jpg";      String f="F://200903300012//pics//201006//";     File file=new File(f);          if(file.exists()){        File[] filelist=file.listFiles();   for(int i=0;i<filelist.length;i++){          String n=filelist[i].getName();   Tosmallerpic(f,filelist[i],"_middle",n,185,160,(float)0.7);    Tosmallerpic(f,filelist[i],"_small",n,45,45,(float)0.7);    Tosmallerpic(f,filelist[i],"_smaller",n,116,100,(float)0.7);    }        }    }
}  
第一次修改后的代码:
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;  /** * * @author WQ *  * @date 2011-01-14 * @versions 1.0 图片压缩工具类 提供的方法中可以设定生成的 缩略图片的大小尺寸、压缩尺寸的比例、图片的质量等 */
public class ImageUtil {  /** * * 图片文件读取 *  * @param srcImgPath * @return */  private static BufferedImage InputImage(String srcImgPath) {  BufferedImage srcImage = null;  try {  // 构造BufferedImage对象  File file = new File(srcImgPath);  FileInputStream in = new FileInputStream(file);  byte[] b = new byte[5];  in.read(b);  srcImage = javax.imageio.ImageIO.read(file);  } catch (IOException e) {  System.out.println("读取图片文件出错!" + e.getMessage());  e.printStackTrace();  }  return srcImage;  }  /** * * 将图片按照指定的图片尺寸、源图片质量压缩(默认质量为1) *  * @param srcImgPath *            :源图片路径 * @param outImgPath *            :输出的压缩图片的路径 * @param new_w *            :压缩后的图片宽 * @param new_h *            :压缩后的图片高 */  public static void Tosmallerpic(String srcImgPath, String outImgPath,  int new_w, int new_h) {  Tosmallerpic(srcImgPath, outImgPath, new_w, new_h, 1F);  }  /** * 将图片按照指定的尺寸比例、源图片质量压缩(默认质量为1) *  * @param srcImgPath *            :源图片路径 * @param outImgPath *            :输出的压缩图片的路径 * @param ratio *            :压缩后的图片尺寸比例 * @param per *            :百分比 */  public static void Tosmallerpic(String srcImgPath, String outImgPath,  float ratio) {  Tosmallerpic(srcImgPath, outImgPath, ratio, 1F);  }  /** * 将图片按照指定长或者宽的最大值来压缩图片(默认质量为1) *  * @param srcImgPath *            :源图片路径 * @param outImgPath *            :输出的压缩图片的路径 * @param maxLength *            :长或者宽的最大值 * @param per *            :图片质量 */  public static void Tosmallerpic(String srcImgPath, String outImgPath,  int maxLength) {  Tosmallerpic(srcImgPath, outImgPath, maxLength, 1F);  }  /** * * 将图片按照指定的图片尺寸、图片质量压缩 *  * @param srcImgPath *            :源图片路径 * @param outImgPath *            :输出的压缩图片的路径 * @param new_w *            :压缩后的图片宽 * @param new_h *            :压缩后的图片高 * @param per *            :百分比 */  public static void Tosmallerpic(String srcImgPath, String outImgPath,  int new_w, int new_h, float per) {  // 得到图片  BufferedImage src = InputImage(srcImgPath);  int old_w = src.getWidth();  // 得到源图宽  int old_h = src.getHeight();  // 得到源图长  // 根据原图的大小生成空白画布  BufferedImage tempImg = new BufferedImage(old_w, old_h,  BufferedImage.TYPE_INT_RGB);  // 在新的画布上生成原图的缩略图  Graphics2D g = tempImg.createGraphics();  g.setColor(Color.white);  g.fillRect(0, 0, old_w, old_h);  g.drawImage(src, 0, 0, old_w, old_h, Color.white, null);  g.dispose();  BufferedImage newImg = new BufferedImage(new_w, new_h,  BufferedImage.TYPE_INT_RGB);  newImg.getGraphics().drawImage(  tempImg.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH), 0,  0, null);  // 调用方法输出图片文件  OutImage(outImgPath, newImg, per);  }  /** * * 将图片按照指定的尺寸比例、图片质量压缩 *  * @param srcImgPath *            :源图片路径 * @param outImgPath *            :输出的压缩图片的路径 * @param ratio *            :压缩后的图片尺寸比例 * @param per *            :百分比 */  public static void Tosmallerpic(String srcImgPath, String outImgPath,  float ratio, float per) {  // 得到图片  BufferedImage src = InputImage(srcImgPath);  int old_w = src.getWidth();  // 得到源图宽  int old_h = src.getHeight();  // 得到源图长  int new_w = 0;  // 新图的宽  int new_h = 0;  // 新图的长  BufferedImage tempImg = new BufferedImage(old_w, old_h,  BufferedImage.TYPE_INT_RGB);  Graphics2D g = tempImg.createGraphics();  g.setColor(Color.white);  // 从原图上取颜色绘制新图g.fillRect(0, 0, old_w, old_h);  g.drawImage(src, 0, 0, old_w, old_h, Color.white, null);  g.dispose();  // 根据图片尺寸压缩比得到新图的尺寸new_w = (int) Math.round(old_w * ratio);  new_h = (int) Math.round(old_h * ratio);  BufferedImage newImg = new BufferedImage(new_w, new_h,  BufferedImage.TYPE_INT_RGB);  newImg.getGraphics().drawImage(  tempImg.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH), 0,  0, null);  // 调用方法输出图片文件OutImage(outImgPath, newImg, per);  }  /** * * 指定长或者宽的最大值来压缩图片 *  * @param srcImgPath *            :源图片路径 * @param outImgPath *            :输出的压缩图片的路径 * @param maxLength *            :长或者宽的最大值 * @param per *            :图片质量 */  public static void Tosmallerpic(String srcImgPath, String outImgPath,  int maxLength, float per) {  // 得到图片  BufferedImage src = InputImage(srcImgPath);  int old_w = src.getWidth();  // 得到源图宽  int old_h = src.getHeight();  // 得到源图长  int new_w = 0;  // 新图的宽  int new_h = 0;  // 新图的长  BufferedImage tempImg = new BufferedImage(old_w, old_h,  BufferedImage.TYPE_INT_RGB);  Graphics2D g = tempImg.createGraphics();  g.setColor(Color.white);  // 从原图上取颜色绘制新图  g.fillRect(0, 0, old_w, old_h);  g.drawImage(src, 0, 0, old_w, old_h, Color.white, null);  g.dispose();  // 根据图片尺寸压缩比得到新图的尺寸  if (old_w > old_h) {  // 图片要缩放的比例  new_w = maxLength;  new_h = (int) Math.round(old_h * ((float) maxLength / old_w));  } else {  new_w = (int) Math.round(old_w * ((float) maxLength / old_h));  new_h = maxLength;  }  BufferedImage newImg = new BufferedImage(new_w, new_h,  BufferedImage.TYPE_INT_RGB);  newImg.getGraphics().drawImage(  tempImg.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH), 0,  0, null);  // 调用方法输出图片文件  OutImage(outImgPath, newImg, per);  }  /** * * 将图片文件输出到指定的路径,并可设定压缩质量 *  * @param outImgPath * @param newImg * @param per */  private static void OutImage(String outImgPath, BufferedImage newImg,  float per) {  // 判断输出的文件夹路径是否存在,不存在则创建  File file = new File(outImgPath);  if (!file.getParentFile().exists()) {  file.getParentFile().mkdirs();  }// 输出到文件流  try {  FileOutputStream newimage = new FileOutputStream(outImgPath);  JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);  JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(newImg);  // 压缩质量  jep.setQuality(per, true);  encoder.encode(newImg, jep);  newimage.close();  } catch (FileNotFoundException e) {  // TODO Auto-generated catch blocke.printStackTrace();  } catch (ImageFormatException e) {  // TODO Auto-generated catch blocke.printStackTrace();  } catch (IOException e) {  // TODO Auto-generated catch blocke.printStackTrace();  }  }  public static void main(String args[]) {  String f = "c:/img/";  File file = new File(f);  if (file.exists()) {  File[] filelist = file.listFiles();  for (int i = 0; i < filelist.length; i++) {  File fi = filelist[i];  System.out.println(fi.length());  String n = filelist[i].getName();  // Tosmallerpic(f, filelist[i], "_ratio_small", n,  // 0.303,(float)0.7);  // Tosmallerpic(f, filelist[i], "_ratio_smaller", n,  // 0.083,(float)0.7);  }  }  String srcImg = "c:/img/car_2.jpg";  String tarDir = "c:/img/newImg/";  long startTime = new Date().getTime();  Tosmallerpic(srcImg, tarDir + "car_1_maxLength_1.jpg", 400);  Tosmallerpic(srcImg, tarDir + "car_1_maxLength_2.jpg", 0.5F);  Tosmallerpic(srcImg, tarDir + "car_1_maxLength_3.jpg", 400, 500);  Tosmallerpic(srcImg, tarDir + "car_1_maxLength_11.jpg", 400, 0.7F);  Tosmallerpic(srcImg, tarDir + "car_1_maxLength_22.jpg", 0.5F, 0.8F);  Tosmallerpic(srcImg, tarDir + "car_1_maxLength_33.jpg", 400, 500, 0.8F);  System.out.println(new Date().getTime() - startTime);  }
}  
第二次修改,只是对长宽尺寸压缩,按原图片质量
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.imageio.ImageIO;  /** * * @author WQ * @date 2011-01-14 * @versions 1.0 图片压缩工具类 提供的方法中可以设定生成的 * 缩略图片的大小尺寸等 */
public class ImageUtil {  /** * 图片文件读取 * * @param srcImgPath * @return */  private static BufferedImage InputImage(String srcImgPath) {  BufferedImage srcImage = null;  try {  FileInputStream in = new FileInputStream(srcImgPath);  srcImage = javax.imageio.ImageIO.read(in);  } catch (IOException e) {  System.out.println("读取图片文件出错!" + e.getMessage());  e.printStackTrace();  }  return srcImage;  }  /** * * 将图片按照指定的图片尺寸压缩 * * @param srcImgPath :源图片路径 * @param outImgPath * * :输出的压缩图片的路径 * @param new_w * :压缩后的图片宽 * @param new_h * :压缩后的图片高 */  public static void compressImage(String srcImgPath, String outImgPath,  int new_w, int new_h) {  BufferedImage src = InputImage(srcImgPath);  disposeImage(src, outImgPath, new_w, new_h);  }  /** * * 指定长或者宽的最大值来压缩图片 * * @param srcImgPath * :源图片路径 * @param outImgPath * * :输出的压缩图片的路径 * @param maxLength * :长或者宽的最大值 */  public static void compressImage(String srcImgPath, String outImgPath,  int maxLength) {  // 得到图片  BufferedImage src = InputImage(srcImgPath);  if (null != src) {  int old_w = src.getWidth();  // 得到源图宽  int old_h = src.getHeight();  // 得到源图长  int new_w = 0;  // 新图的宽  int new_h = 0;  // 新图的长  // 根据图片尺寸压缩比得到新图的尺寸  if (old_w > old_h) {  // 图片要缩放的比例  new_w = maxLength;  new_h = (int) Math.round(old_h * ((float) maxLength / old_w));  } else {  new_w = (int) Math.round(old_w * ((float) maxLength / old_h));  new_h = maxLength;  }  disposeImage(src, outImgPath, new_w, new_h);  }  }  /** * 处理图片 * * @param src * @param outImgPath * @param new_w * @param new_h */  private synchronized static void disposeImage(BufferedImage src,  String outImgPath, int new_w, int new_h) {  // 得到图片  int old_w = src.getWidth();  // 得到源图宽  int old_h = src.getHeight();  // 得到源图长  BufferedImage newImg = null;  // 判断输入图片的类型  switch (src.getType()) {  case 13:  // png,gifnewImg = new BufferedImage(new_w, new_h,  // BufferedImage.TYPE_4BYTE_ABGR);  break;  default:  newImg = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB);  break;  }  Graphics2D g = newImg.createGraphics();  // 从原图上取颜色绘制新图  g.drawImage(src, 0, 0, old_w, old_h, null);  g.dispose();  // 根据图片尺寸压缩比得到新图的尺寸  newImg.getGraphics().drawImage(  src.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH), 0, 0,  null);  // 调用方法输出图片文件  OutImage(outImgPath, newImg);  }  /** * * 将图片文件输出到指定的路径,并可设定压缩质量 * * @param outImgPath * @param newImg * @param * per */  private static void OutImage(String outImgPath, BufferedImage newImg) {  // 判断输出的文件夹路径是否存在,不存在则创建  File file = new File(outImgPath);  if (!file.getParentFile().exists()) {  file.getParentFile().mkdirs();  }// 输出到文件流  try {  ImageIO.write(newImg, outImgPath.substring(outImgPath  .lastIndexOf(".") + 1), new File(outImgPath));  } catch (FileNotFoundException e) {  e.printStackTrace();  } catch (IOException e) {  e.printStackTrace();  }  }
}  
另见参考:http://www.javaeye.com/topic/266585

java 程序实现对图片的压缩生成缩略图并可设定长宽、尺寸压缩率、图片质量相关推荐

  1. java程序实现给图片添加logo

    java程序实现给图片添加logo 练习需求: 拿到一张图片,给图片添加上水印信息 package com.zcl.newDemo;import javax.imageio.ImageIO; impo ...

  2. php imagick 缩略图,PHP Imagick完美实现图片裁切、生成缩略图、添加水印,

    PHP Imagick完美实现图片裁切.生成缩略图.添加水印, 本文实例讲解了PHP使用Imagick 裁切.生成缩略图.添加水印自动检测和处理,支持gif,分享给大家供大家参考,具体内容如下 调用方 ...

  3. java获取图片的长宽尺寸(毫米)

    java获取图片的长宽尺寸(毫米) 现在有个需求是附上 附件图片,同时要标注图片的一些属性,比较麻烦的要标识图片的长宽尺寸(毫米),网上找了半天都是获取图片的长宽像素,但是想了想 图片的长宽尺寸不应该 ...

  4. 怎么修改图片长宽尺寸?如何用电脑修改照片尺寸?

    自媒体编辑工作的小伙伴经常需要修改图片尺寸(https://www.yasuotu.com/size)来应对不同平台的图片尺寸大小要求,那么如何改图片大小呢?接下来本文将带给大家一些关于图片改大小的相 ...

  5. java程序中的图片与数值关联_Java从图片中读取图片的元数据Exif信息

    一般情况下是java程序读取不到gps等扩展信息的.如果想要解析到里面的信息需要下载一个jar包,metadata-extractor-2.6.4.jar(下载地址: http://code.goog ...

  6. 微信小程序中裁剪图片以及压缩到指定尺寸并上传

    本文分为两个内容,分别是裁剪图片和压缩 引出问题 1.为何要裁剪图片 因为需要上传头像,但是每个型号的手机拍出来的照片尺寸都不太一样,不能统一,所以,希望在上传之前进行自主裁剪,保证上传到服务器上的尺 ...

  7. 后端生成图片验证码,Kotlin生成图片验证码,Java生成图片验证码,图片验证码的生成和校验

    后端生成图片验证码 注:以下代码主要使用kotlin进行编写,kotlin可兼容java,可以直接使用.IDEA也支持将java与kotlin代码进行互相转换. 1.引入依赖: Gradle(若你使用 ...

  8. java线程池下载图片,压缩图片大小

    java对于线程池下载图片,以及图片的压缩,删除 其中引用了thumbnailator 来进行压缩减少了我们工作量 maven地址 <!-- https://mvnrepository.com/ ...

  9. 小程序选择手机图片后 压缩图片 转码base64

    xml: <canvas canvas-id="attendCanvasId" style="width:375rpx;height:520rpx;position ...

最新文章

  1. Centos 6启动流程详解
  2. python学会了可以做什么菜_python学习之路(24)
  3. There was a problem confirming the ssl certificate
  4. 如何使用Navicat恢复数据库脚本
  5. Django中使用极验Geetest滑动验证码
  6. LeetCode 973. 最接近原点的 K 个点(排序/优先队列/快排)
  7. TortoiseGit 将工作区变动文件提交本地仓库_入门试炼_04
  8. 类的实例属性和类属性的区别
  9. Linux “百变”秀:今天 Windows 95,明天 Mac OS 9
  10. Java数组3(2015-8-27)
  11. windows 下关闭135 139 445等危险端口
  12. cs起源 css武器大合集,cs起源幻彩武器包mod
  13. 比较全的敏捷概念知识总结
  14. chrome插件安装方法教程
  15. 综合实验:LVS+LAMP+NFS+MySQL读写分离
  16. 我的钱包页面HTML,我的钱包.html
  17. 联通路由如何设置虚拟服务器,联通光纤安装路由器怎么设置_联通光纤怎么连接无线路由器?-192路由网...
  18. matlab grab cut,matlabGrabCutS graph 算法, 编写,可以运 能直观看到结果。 272万源代码下载- www.pudn.com...
  19. 32位操作系统升级为64位步奏
  20. 论文解读 - 城市自动驾驶车辆运动规划与控制技术综述 (第1部分)

热门文章

  1. vector容器中关于处理从非0位置开始赋值的操作
  2. 7-17 汉诺塔的非递归实现 (25 分)(思路分析)
  3. [C++11]智能指针简单介绍
  4. ios::sync_with_stdio(false)的作用
  5. 连接mysql数据库_解决Navicat连接MySQL数据库报错问题
  6. 电机控制pid_微电机控制如此简单,揭秘微电机调速的控制,PID控制之双环调速...
  7. 操作系统——内存管理——分段和分页
  8. #3551. [ONTAK2010]Peaks加强版(kruskal 重构树 + 主席树)
  9. 牛客挑战赛30 C 小G砍树 换根dp+组合
  10. GCD HDU - 1695