java实现方便、快捷的图片编辑

来源:互联网 发布:网络拓扑结构有哪几种 编辑:程序博客网 时间:2024/06/06 21:41

在现在的开发中,图片的表现形式也是越来越多,随之而来的是图片的版权的问题,所以,不少的网站将自己的图片在上传的时候,打上专有的水印(如左图)。而作为图片的预览,需要有对应的适合大小的缩略图。以前在写一个blog的时候,用到了一个很好用的包,是一个外国人写的。
    首先,下载ij.jar(本站提供下载,将ij.jar.rar改为ij.jar即可),同时,我将两个重要的操作类的源码提取出来了,方便大家参考。
    我的这个文件的作用是从我的pc论坛上将图片取下来,然后修改成对应的小图片,提供給手机用户浏览(wap)。要做成什么效果,打什么水印,什么大小,在代码做对应的配置即可,也可以把这些抽取出来,形成一个properties文件。

 

  1. **  
  2.  * @author   
  3.  * @company   leemenz (C) copyright  
  4.  * @time      2006-8-23  15:18:01  
  5.  * @version   1.0.0.0  
  6.  * @package   com.xxx.tools  
  7.  */  
  8.   
  9. package com.xxx.imageDeal;   
  10.   
  11. import ij.ImagePlus;   
  12. import ij.io.Opener;   
  13. import ij.process.ImageProcessor;   
  14.   
  15. import java.awt.Font;   
  16. import java.awt.Graphics;   
  17. import java.awt.image.BufferedImage;   
  18. import java.io.DataInputStream;   
  19. import java.io.File;   
  20. import java.io.FileInputStream;   
  21. import java.io.FileOutputStream;   
  22. import java.io.IOException;   
  23. import java.net.HttpURLConnection;   
  24.   
  25.     
  26. import java.net.InetAddress;   
  27. import java.net.MalformedURLException;   
  28. import java.net.URL;   
  29. import com.sun.image.codec.jpeg.JPEGCodec;   
  30. import com.sun.image.codec.jpeg.JPEGEncodeParam;   
  31. import com.sun.image.codec.jpeg.JPEGImageEncoder;   
  32. import com.xxx.database.SqlHelper;   
  33. import com.xxx.util.Constants;   
  34. import com.xxx.util.Tools;   
  35.   
  36.   
  37. public class ImageTool {   
  38.   /**  
  39.    * 对远程图片的处理(下载到本地,缩小操作等)  
  40.    *   
  41.    * @author 李国庆  
  42.    * @param urlpic  
  43.    *            图片的URL地址 列如:http://ggbm.programfan.com/images/11145416530.gif  
  44.    * @param rootid  
  45.    *            论坛主贴ID  
  46.    */  
  47.   public static void getPic(String urlpic, String rootid) {   
  48.   
  49.     // //在图片关系表中确定原始URL与自己网站上URL的对应关系,关系存在则从WAP_HSOL_RELATION表//   
  50.     // //中读图片信息,关系不存在则继续执行图片下载和缩小操作////////////////////////////////   
  51.     if (getRelation(urlpic) || judgeUrl(urlpic)) {   
  52.       return;   
  53.     }   
  54.     // //////////////////////////////////////////////////////////////////////////////   
  55.   
  56.     String first = urlpic.substring(7);   
  57.     int end = first.indexOf("/");   
  58.     String urlp = first.substring(end + 1);   
  59.   
  60.     int index = urlp.lastIndexOf("/");   
  61.     String smallFileName = "/picpath/" + urlp.substring(0, index + 1)   
  62.         + "small" + urlp.substring(index + 1); // 得到下载到本地的图片的URL   
  63.   
  64.     // ////////////////////////////图片的远程读入//////////////////////////////////////   
  65.     HttpURLConnection urlCon = null;   
  66.     URL url = null;   
  67.     DataInputStream ir = null;   
  68.   
  69.     String[] pp = anlizeUrl(urlpic);   
  70.     StringBuffer middle = new StringBuffer();   
  71.     for (int i = 0; i < pp.length - 1; i++) {   
  72.       middle.append(pp[i] + File.separatorChar);   
  73.     }   
  74.   
  75.     Tools manage = new Tools();   
  76.     manage.createPath(Constants.OUTPUT_PICTURE_PATH + File.separatorChar   
  77.         + middle.toString());   
  78.   
  79.     int last = urlpic.lastIndexOf("/");   
  80.     String str = urlpic.substring(last + 1);   
  81.     String newName = Constants.OUTPUT_PICTURE_PATH + File.separatorChar   
  82.         + middle.toString() + str;   
  83.   
  84.     File newFile = new File(newName);   
  85.   
  86.     try {   
  87.       FileOutputStream fw = null;   
  88.       try {   
  89.         fw = new FileOutputStream(newFile);   
  90.       } catch (IOException e) {   
  91.         e.printStackTrace();   
  92.       }   
  93.       url = new URL(urlpic);   
  94.       urlCon = (HttpURLConnection) url.openConnection();   
  95.   
  96.       // 对远程图片是否存在的判断   
  97.       if (urlCon.getResponseCode() / 100 == 4) {   
  98.         System.out.println("对不起,图片地址不存在!请核对!");   
  99.         return;   
  100.       }   
  101.   
  102.       ir = new DataInputStream(urlCon.getInputStream());   
  103.       int c = ir.read();   
  104.       while (c != -1) {   
  105.         fw.write(c);   
  106.         c = ir.read();   
  107.       }   
  108.   
  109.       fw.close();   
  110.       ir.close();   
  111.     } catch (MalformedURLException e) {   
  112.       e.printStackTrace();   
  113.       System.out.println("123");   
  114.     } catch (IOException ioe) {   
  115.       ioe.printStackTrace();   
  116.       System.out.println("456");   
  117.     }   
  118.     // //////////////////////////////////////////////////////////////////////////////   
  119.   
  120.     // 图片的缩小   
  121.     String ppr = urlpic.toLowerCase();   
  122.     if (ppr.endsWith(".jpg") || ppr.endsWith(".jpeg")   
  123.         || ppr.endsWith(".png") || ppr.endsWith(".gif")) {   
  124.       try {   
  125.         dealImage(newName);   
  126.       } catch (Exception e) {   
  127.         System.out   
  128.             .println(" com.leemenz.hsol.image.ImageTool getPic(String urlpic, String rootid) abc,e: "  
  129.                 + e);   
  130.       }   
  131.     }   
  132.     try {   
  133.       if (urlCon.getResponseCode() == 200  
  134.           || urlCon.getResponseCode() == 0) {   
  135.         SqlHelper.executeUpdate(urlpic, smallFileName);   
  136.       }   
  137.     } catch (Exception e) {   
  138.       System.out.println("数据库操作失败: " + e);   
  139.     }   
  140.   }   
  141.   
  142.   /**  
  143.    * 截取url地址段,以”/“为标记  
  144.    * @param url  
  145.    * @return  
  146.    */  
  147.   public static String[] anlizeUrl(String url) {   
  148.     String first = url.substring(7);   
  149.     int end = first.indexOf("/");   
  150.     url = first.substring(end + 1);   
  151.   
  152.     String[] str = url.split("/");   
  153.     return str;   
  154.   }   
  155.   
  156.   /**  
  157.    * 获得访问ip  
  158.    * @param host  
  159.    * @return  
  160.    */  
  161.   public static String getIP(String host) {   
  162.     String first = host.substring(7);   
  163.     int end = first.indexOf("/");   
  164.     String hostaddress = first.substring(0, end);   
  165.     String str = "";   
  166.     try {   
  167.       InetAddress[] address = InetAddress.getAllByName(hostaddress);   
  168.       str = address[0].getHostAddress();   
  169.       host = host.replaceAll(hostaddress, str);   
  170.     } catch (Exception e) {   
  171.       System.out.println(e.toString());   
  172.     }   
  173.     return host;   
  174.   }   
  175.   
  176.   // //////////////////////////////////////////////////////////////////////////////   
  177.   
  178.   // //////////////////////////////图片缩小处理//////////////////////////////////////   
  179.   
  180.      
  181.   /**  
  182.    * // 处理GIF图片  
  183.    */  
  184.   public static void dealGif(String srcFile) throws Exception {   
  185.     int index = srcFile.lastIndexOf(File.separatorChar);   
  186.     String smallFileName = srcFile.substring(0, index + 1) + "small"  
  187.         + srcFile.substring(index + 1);   
  188.     File delfile = new File(srcFile);   
  189.     GifDecoder d = new GifDecoder();   
  190.     d.read(srcFile);   
  191.     int frameCount = d.getFrameCount();   
  192.     // ImageStack stack = null;   
  193.     for (int i = 0; i < frameCount; i++) {   
  194.       d.getFrame(i);   
  195.       // if (i==0)   
  196.       // stack = new ImageStack(frame.getWidth(), frame.getHeight());   
  197.       d.getDelay(i); // display duration of frame in milliseconds   
  198.       // stack.addSlice(null, frame);   
  199.     }   
  200.   
  201.     int width = d.getFrame(0).getWidth();   
  202.     if (width <= 128) {   
  203.       copyFile(srcFile, smallFileName); // 按原样拷贝,不用压缩   
  204.       delfile.delete();   
  205.     } else {   
  206.       saveToFile(d, 128, smallFileName); // 生成小图   
  207.       delfile.delete();   
  208.     }   
  209.   }   
  210.   
  211.   /**  
  212.    * 复制文件  
  213.    * @param srcFile  
  214.    * @param destFile  
  215.    */  
  216.   private static void copyFile(String srcFile, String destFile) {   
  217.     FileOutputStream fos = null;   
  218.     FileInputStream fis = null;   
  219.     try {   
  220.       fis = new FileInputStream(srcFile);   
  221.       fos = new FileOutputStream(destFile);   
  222.       byte[] bytes = new byte[2000];   
  223.       int readCount = 0;   
  224.       while (readCount >= 0) {   
  225.         readCount = fis.read(bytes);   
  226.         fos.write(bytes, 0, readCount);   
  227.         fos.flush();   
  228.       }   
  229.     } catch (Exception ee) {   
  230.       System.out.println("hsolJava,ImageTool,copyFile,ee:" + ee);   
  231.     } finally {   
  232.       try {   
  233.         fos.close();   
  234.       } catch (Exception eee) {   
  235.       }   
  236.       try {   
  237.         fis.close();   
  238.       } catch (Exception eee) {   
  239.       }   
  240.     }   
  241.   
  242.   }   
  243.   
  244.   /**  
  245.    * // 对一个图片文件进行加工(非gif文件)  
  246.    * @param srcFile  
  247.    * @throws Exception  
  248.    */  
  249.   public static void dealImage(String srcFile) throws Exception {   
  250.     System.out   
  251.         .println(" com.leemenz.hsol.image dealImage(String srcFile) srcFile is "  
  252.             + srcFile);   
  253.     if (srcFile.endsWith("gif")) { // 是gif文件   
  254.       dealGif(srcFile);   
  255.       return;   
  256.     }   
  257.   
  258.     if (!(srcFile.endsWith(".jpg") || srcFile.endsWith(".jpeg"))) {   
  259.       int index0 = srcFile.lastIndexOf('.');   
  260.       File f = new File(srcFile);   
  261.       srcFile = srcFile.substring(0, index0 + 1) + "jpg";   
  262.       f.renameTo(new File(srcFile));   
  263.     }   
  264.     File delfile = new File(srcFile);   
  265.     int index = srcFile.lastIndexOf(File.separatorChar);   
  266.     String smallFileName = srcFile.substring(0, index + 1) + "small"  
  267.         + srcFile.substring(index + 1);   
  268.   
  269.     Opener o = new Opener();   
  270.     ImagePlus imp = o.openImage(srcFile);   
  271.     ImageProcessor ip = imp.getProcessor();   
  272.   
  273.     int width = (int) (ip.getWidth());   
  274.     int height = (int) (ip.getHeight());   
  275.     ImageProcessor tmpIP = null;   
  276.   
  277.     if (width <= 128) {   
  278.       saveToFile(ip.duplicate(), smallFileName);   
  279.       delfile.delete();   
  280.     } else {   
  281.       // 压缩生成一个small文件   
  282.       double d = 128d / width;   
  283.       tmpIP = ip.resize((int) (width * d), (int) (height * d));   
  284.       saveToFile(tmpIP, smallFileName);   
  285.   
  286.       delfile.delete();   
  287.     }   
  288.   } // end of method   
  289.   
  290.   /**  
  291.    * // 保存GIF文件  
  292.    * @param d  
  293.    * @param width  
  294.    * @param destFile  
  295.    */  
  296.   private static void saveToFile(GifDecoder d, int width, String destFile) {   
  297.     GifEncoder encoder = new GifEncoder();   
  298.     encoder.setRepeat(d.loopCount);   
  299.     encoder.setDelay(d.delay);   
  300.   
  301.     encoder.start(destFile);   
  302.   
  303.     ImageProcessor ip = null;   
  304.     ImageProcessor frame = d.getFrame(0);   
  305.     double fWidth = frame.getWidth() * 1.0;   
  306.     double fHeight = frame.getHeight() * 1.0;   
  307.     double ratio = width / fWidth;   
  308.   
  309.     for (int i = 0; i < d.getFrameCount(); i++) {   
  310.       ip = d.getFrame(i);   
  311.       ip = ip.resize((int) (fWidth * ratio), (int) (fHeight * ratio));   
  312.       encoder.addFrame(new ImagePlus("t" + i, ip));   
  313.     }   
  314.     encoder.finish();   
  315.   }   
  316.   
  317.   // 保存JPG文件   
  318.   private static void saveToFile(ImageProcessor ip, String destFile) {   
  319.     int index = destFile.lastIndexOf('.');   
  320.     String type = destFile.substring(index + 1);   
  321.     if (!(type.equals("jpg") || type.equals("jpeg"))) {   
  322.       destFile = destFile.substring(0, index + 1) + "jpg";   
  323.     }   
  324.   
  325.     FileOutputStream fos = null;   
  326.     try {   
  327.       fos = new FileOutputStream(destFile);   
  328.       BufferedImage bi = new BufferedImage(ip.getWidth(), ip.getHeight(),   
  329.           BufferedImage.TYPE_INT_RGB);   
  330.   
  331.       Graphics g = bi.createGraphics();   
  332.       g.drawImage(ip.createImage(), 00null);   
  333.   
  334.       String logo = "Powered by Leo";   
  335.       int width = ip.getWidth();   
  336.       if (width <= 128) {   
  337.         if (width >= 103) {   
  338.           g.setFont(new Font("SansSerif", Font.PLAIN, 12));   
  339.           g.drawString(logo, ip.getWidth() - 102, ip.getHeight() - 3);   
  340.         }   
  341.       } else if (width <= 300) {   
  342.         g.setFont(new Font("SansSerif", Font.BOLD, 14));   
  343.         g.drawString(logo, ip.getWidth() - 127, ip.getHeight() - 8);   
  344.       } else {   
  345.         g.setFont(new Font("SansSerif", Font.BOLD, 16));   
  346.         g.drawString(logo, ip.getWidth() - 145, ip.getHeight() - 8);   
  347.       }   
  348.   
  349.       g.dispose();   
  350.   
  351.       JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);   
  352.       JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);   
  353.       param.setQuality(0.885f, true);   
  354.       encoder.encode(bi, param);   
  355.   
  356.     } catch (Exception e) {   
  357.       System.out.println("saveToFile(),保存文件失败,e: ");   
  358.       e.printStackTrace();   
  359.     } finally {   
  360.       if (fos != null) {   
  361.         try {   
  362.           fos.close();   
  363.         } catch (Exception eeee) {   
  364.         }   
  365.       }   
  366.     }   
  367.   } // end of method   
  368.   
  369.   /**  
  370.    * 判断图片是否已经被处理,如果已经处理,则直接读取本地图片  
  371.    * @param imgurl  
  372.    * @return  
  373.    */  
  374.   public static boolean getRelation(String imgurl) {   
  375.     boolean state = true;   
  376.     try {   
  377.       if (SqlHelper.ifExist(imgurl)) {   
  378.         state = false;   
  379.       }   
  380.     } catch (Exception ee) {   
  381.       System.out.println("ImageTool,getRelation(): " + ee);   
  382.     }   
  383.     return state;   
  384.   }   
  385.   
  386.   /**  
  387.    * 判断url地址是否合法  
  388.    * @param url  
  389.    * @return  
  390.    */  
  391.   private static boolean judgeUrl(String url) {   
  392.     boolean state = false;   
  393.     if (url.startsWith("http://")) {   
  394.       int ascii = 0;   
  395.       char data[] = url.toCharArray();   
  396.       for (int i = 0; i < data.length; i++) {   
  397.         ascii = (int) data[i];   
  398.         if (ascii > 128) {   
  399.           state = true;   
  400.           break;   
  401.         }   
  402.       }   
  403.     } else {   
  404.       state = true;   
  405.     }   
  406.     return state;   
  407.   }   
  408.   
  409. }  
原创粉丝点击