网上图片本地保存并进行压缩操作

来源:互联网 发布:重庆时时彩网络大平台 编辑:程序博客网 时间:2024/06/06 00:33
package com.demo.wnb;import java.awt.Graphics2D;import java.awt.Image;import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import java.util.HashMap;import java.util.Map;import javax.imageio.ImageIO;public class PictureCompress {public static void main(String args[]) {          try {          getPic("http://pic.58pic.com/58pic/16/62/63/97m58PICyWM_1024.jpg");            Map<Integer, String> map = readfile("C:/Users/wnb/Desktop/pic", null);              for (int i = 0; i < map.size(); i++) {                 compressImage(map.get(i), "C:/Users/wnb/Desktop/_" + i + ".png", 100, 75);                //compressImage(map.get(i), "C:/Users/wnb/Desktop/_" + i + ".png", 100);              }          } catch (Exception e) {          e.printStackTrace();        }      }private static void getPic(String path) throws Exception{URL url = new URL(path);  //new一个URL对象HttpURLConnection conn = (HttpURLConnection)url.openConnection();//打开链接    conn.setRequestMethod("GET");  //设置请求方式为"GET" conn.setConnectTimeout(5 * 1000);  //超时响应时间为5秒  InputStream inStream = conn.getInputStream(); //通过输入流获取图片数据   byte[] data = readInputStream(inStream);  //得到图片的二进制数据,以二进制封装得到数据,具有通用性File file = new File("C:\\Users\\wnb\\Desktop\\pic");  //new一个文件对象用来保存图片,默认保存当前工程根目录 if (!file.exists()){//若此目录不存在,则创建  file.mkdir();          }File imageFile = new File("C:\\Users\\wnb\\Desktop\\pic\\1.jpg");FileOutputStream outStream = new FileOutputStream(imageFile);//创建输出流  outStream.write(data);  //写入数据  outStream.close();//关闭输出流  }public static byte[] readInputStream(InputStream inStream) throws Exception{          ByteArrayOutputStream outStream = new ByteArrayOutputStream();          byte[] buffer = new byte[1024];  //创建一个Buffer字符串          int len = 0;  //每次读取的字符串长度,如果为-1,代表全部读取完毕         //使用一个输入流从buffer里把数据读取出来          while( (len=inStream.read(buffer)) != -1 ){              outStream.write(buffer, 0, len);  //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度         }          inStream.close(); //关闭输入流            return outStream.toByteArray();  //把outStream里的数据写入内存      }                  /**       * 图片文件读取       * @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) {              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,gif格式        //newImg = 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();          }      }        /**     * 图片路径读取     * @param filepath     * @param pathMap     * @return     * @throws Exception     */    public static Map<Integer, String> readfile(String filepath,              Map<Integer, String> pathMap) throws Exception {          if (pathMap == null) {              pathMap = new HashMap<Integer, String>();          }          File file = new File(filepath);          // 文件          if (!file.isDirectory()) {              pathMap.put(pathMap.size(), file.getPath());            } else if (file.isDirectory()) { // 如果是目录, 遍历所有子目录取出所有文件名              String[] filelist = file.list();              for (int i = 0; i < filelist.length; i++) {                  File readfile = new File(filepath + "/" + filelist[i]);                  if (!readfile.isDirectory()) {                      pathMap.put(pathMap.size(), readfile.getPath());                  } else if (readfile.isDirectory()) { // 子目录的目录                      readfile(filepath + "/" + filelist[i], pathMap);                  }              }          }          return pathMap;      }  }
1 0
原创粉丝点击