java实现方便、快捷的图片编辑
来源:互联网 发布:网络拓扑结构有哪几种 编辑:程序博客网 时间:2024/06/06 21:41
在现在的开发中,图片的表现形式也是越来越多,随之而来的是图片的版权的问题,所以,不少的网站将自己的图片在上传的时候,打上专有的水印(如左图)。而作为图片的预览,需要有对应的适合大小的缩略图。以前在写一个blog的时候,用到了一个很好用的包,是一个外国人写的。
首先,下载ij.jar(本站提供下载,将ij.jar.rar改为ij.jar即可),同时,我将两个重要的操作类的源码提取出来了,方便大家参考。
我的这个文件的作用是从我的pc论坛上将图片取下来,然后修改成对应的小图片,提供給手机用户浏览(wap)。要做成什么效果,打什么水印,什么大小,在代码做对应的配置即可,也可以把这些抽取出来,形成一个properties文件。
- **
- * @author
- * @company leemenz (C) copyright
- * @time 2006-8-23 15:18:01
- * @version 1.0.0.0
- * @package com.xxx.tools
- */
- package com.xxx.imageDeal;
- import ij.ImagePlus;
- import ij.io.Opener;
- import ij.process.ImageProcessor;
- import java.awt.Font;
- import java.awt.Graphics;
- import java.awt.image.BufferedImage;
- import java.io.DataInputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.net.HttpURLConnection;
- import java.net.InetAddress;
- import java.net.MalformedURLException;
- import java.net.URL;
- import com.sun.image.codec.jpeg.JPEGCodec;
- import com.sun.image.codec.jpeg.JPEGEncodeParam;
- import com.sun.image.codec.jpeg.JPEGImageEncoder;
- import com.xxx.database.SqlHelper;
- import com.xxx.util.Constants;
- import com.xxx.util.Tools;
- public class ImageTool {
- /**
- * 对远程图片的处理(下载到本地,缩小操作等)
- *
- * @author 李国庆
- * @param urlpic
- * 图片的URL地址 列如:http://ggbm.programfan.com/images/11145416530.gif
- * @param rootid
- * 论坛主贴ID
- */
- public static void getPic(String urlpic, String rootid) {
- // //在图片关系表中确定原始URL与自己网站上URL的对应关系,关系存在则从WAP_HSOL_RELATION表//
- // //中读图片信息,关系不存在则继续执行图片下载和缩小操作////////////////////////////////
- if (getRelation(urlpic) || judgeUrl(urlpic)) {
- return;
- }
- // //////////////////////////////////////////////////////////////////////////////
- String first = urlpic.substring(7);
- int end = first.indexOf("/");
- String urlp = first.substring(end + 1);
- int index = urlp.lastIndexOf("/");
- String smallFileName = "/picpath/" + urlp.substring(0, index + 1)
- + "small" + urlp.substring(index + 1); // 得到下载到本地的图片的URL
- // ////////////////////////////图片的远程读入//////////////////////////////////////
- HttpURLConnection urlCon = null;
- URL url = null;
- DataInputStream ir = null;
- String[] pp = anlizeUrl(urlpic);
- StringBuffer middle = new StringBuffer();
- for (int i = 0; i < pp.length - 1; i++) {
- middle.append(pp[i] + File.separatorChar);
- }
- Tools manage = new Tools();
- manage.createPath(Constants.OUTPUT_PICTURE_PATH + File.separatorChar
- + middle.toString());
- int last = urlpic.lastIndexOf("/");
- String str = urlpic.substring(last + 1);
- String newName = Constants.OUTPUT_PICTURE_PATH + File.separatorChar
- + middle.toString() + str;
- File newFile = new File(newName);
- try {
- FileOutputStream fw = null;
- try {
- fw = new FileOutputStream(newFile);
- } catch (IOException e) {
- e.printStackTrace();
- }
- url = new URL(urlpic);
- urlCon = (HttpURLConnection) url.openConnection();
- // 对远程图片是否存在的判断
- if (urlCon.getResponseCode() / 100 == 4) {
- System.out.println("对不起,图片地址不存在!请核对!");
- return;
- }
- ir = new DataInputStream(urlCon.getInputStream());
- int c = ir.read();
- while (c != -1) {
- fw.write(c);
- c = ir.read();
- }
- fw.close();
- ir.close();
- } catch (MalformedURLException e) {
- e.printStackTrace();
- System.out.println("123");
- } catch (IOException ioe) {
- ioe.printStackTrace();
- System.out.println("456");
- }
- // //////////////////////////////////////////////////////////////////////////////
- // 图片的缩小
- String ppr = urlpic.toLowerCase();
- if (ppr.endsWith(".jpg") || ppr.endsWith(".jpeg")
- || ppr.endsWith(".png") || ppr.endsWith(".gif")) {
- try {
- dealImage(newName);
- } catch (Exception e) {
- System.out
- .println(" com.leemenz.hsol.image.ImageTool getPic(String urlpic, String rootid) abc,e: "
- + e);
- }
- }
- try {
- if (urlCon.getResponseCode() == 200
- || urlCon.getResponseCode() == 0) {
- SqlHelper.executeUpdate(urlpic, smallFileName);
- }
- } catch (Exception e) {
- System.out.println("数据库操作失败: " + e);
- }
- }
- /**
- * 截取url地址段,以”/“为标记
- * @param url
- * @return
- */
- public static String[] anlizeUrl(String url) {
- String first = url.substring(7);
- int end = first.indexOf("/");
- url = first.substring(end + 1);
- String[] str = url.split("/");
- return str;
- }
- /**
- * 获得访问ip
- * @param host
- * @return
- */
- public static String getIP(String host) {
- String first = host.substring(7);
- int end = first.indexOf("/");
- String hostaddress = first.substring(0, end);
- String str = "";
- try {
- InetAddress[] address = InetAddress.getAllByName(hostaddress);
- str = address[0].getHostAddress();
- host = host.replaceAll(hostaddress, str);
- } catch (Exception e) {
- System.out.println(e.toString());
- }
- return host;
- }
- // //////////////////////////////////////////////////////////////////////////////
- // //////////////////////////////图片缩小处理//////////////////////////////////////
- /**
- * // 处理GIF图片
- */
- public static void dealGif(String srcFile) throws Exception {
- int index = srcFile.lastIndexOf(File.separatorChar);
- String smallFileName = srcFile.substring(0, index + 1) + "small"
- + srcFile.substring(index + 1);
- File delfile = new File(srcFile);
- GifDecoder d = new GifDecoder();
- d.read(srcFile);
- int frameCount = d.getFrameCount();
- // ImageStack stack = null;
- for (int i = 0; i < frameCount; i++) {
- d.getFrame(i);
- // if (i==0)
- // stack = new ImageStack(frame.getWidth(), frame.getHeight());
- d.getDelay(i); // display duration of frame in milliseconds
- // stack.addSlice(null, frame);
- }
- int width = d.getFrame(0).getWidth();
- if (width <= 128) {
- copyFile(srcFile, smallFileName); // 按原样拷贝,不用压缩
- delfile.delete();
- } else {
- saveToFile(d, 128, smallFileName); // 生成小图
- delfile.delete();
- }
- }
- /**
- * 复制文件
- * @param srcFile
- * @param destFile
- */
- private static void copyFile(String srcFile, String destFile) {
- FileOutputStream fos = null;
- FileInputStream fis = null;
- try {
- fis = new FileInputStream(srcFile);
- fos = new FileOutputStream(destFile);
- byte[] bytes = new byte[2000];
- int readCount = 0;
- while (readCount >= 0) {
- readCount = fis.read(bytes);
- fos.write(bytes, 0, readCount);
- fos.flush();
- }
- } catch (Exception ee) {
- System.out.println("hsolJava,ImageTool,copyFile,ee:" + ee);
- } finally {
- try {
- fos.close();
- } catch (Exception eee) {
- }
- try {
- fis.close();
- } catch (Exception eee) {
- }
- }
- }
- /**
- * // 对一个图片文件进行加工(非gif文件)
- * @param srcFile
- * @throws Exception
- */
- public static void dealImage(String srcFile) throws Exception {
- System.out
- .println(" com.leemenz.hsol.image dealImage(String srcFile) srcFile is "
- + srcFile);
- if (srcFile.endsWith("gif")) { // 是gif文件
- dealGif(srcFile);
- return;
- }
- if (!(srcFile.endsWith(".jpg") || srcFile.endsWith(".jpeg"))) {
- int index0 = srcFile.lastIndexOf('.');
- File f = new File(srcFile);
- srcFile = srcFile.substring(0, index0 + 1) + "jpg";
- f.renameTo(new File(srcFile));
- }
- File delfile = new File(srcFile);
- int index = srcFile.lastIndexOf(File.separatorChar);
- String smallFileName = srcFile.substring(0, index + 1) + "small"
- + srcFile.substring(index + 1);
- Opener o = new Opener();
- ImagePlus imp = o.openImage(srcFile);
- ImageProcessor ip = imp.getProcessor();
- int width = (int) (ip.getWidth());
- int height = (int) (ip.getHeight());
- ImageProcessor tmpIP = null;
- if (width <= 128) {
- saveToFile(ip.duplicate(), smallFileName);
- delfile.delete();
- } else {
- // 压缩生成一个small文件
- double d = 128d / width;
- tmpIP = ip.resize((int) (width * d), (int) (height * d));
- saveToFile(tmpIP, smallFileName);
- delfile.delete();
- }
- } // end of method
- /**
- * // 保存GIF文件
- * @param d
- * @param width
- * @param destFile
- */
- private static void saveToFile(GifDecoder d, int width, String destFile) {
- GifEncoder encoder = new GifEncoder();
- encoder.setRepeat(d.loopCount);
- encoder.setDelay(d.delay);
- encoder.start(destFile);
- ImageProcessor ip = null;
- ImageProcessor frame = d.getFrame(0);
- double fWidth = frame.getWidth() * 1.0;
- double fHeight = frame.getHeight() * 1.0;
- double ratio = width / fWidth;
- for (int i = 0; i < d.getFrameCount(); i++) {
- ip = d.getFrame(i);
- ip = ip.resize((int) (fWidth * ratio), (int) (fHeight * ratio));
- encoder.addFrame(new ImagePlus("t" + i, ip));
- }
- encoder.finish();
- }
- // 保存JPG文件
- private static void saveToFile(ImageProcessor ip, String destFile) {
- int index = destFile.lastIndexOf('.');
- String type = destFile.substring(index + 1);
- if (!(type.equals("jpg") || type.equals("jpeg"))) {
- destFile = destFile.substring(0, index + 1) + "jpg";
- }
- FileOutputStream fos = null;
- try {
- fos = new FileOutputStream(destFile);
- BufferedImage bi = new BufferedImage(ip.getWidth(), ip.getHeight(),
- BufferedImage.TYPE_INT_RGB);
- Graphics g = bi.createGraphics();
- g.drawImage(ip.createImage(), 0, 0, null);
- String logo = "Powered by Leo";
- int width = ip.getWidth();
- if (width <= 128) {
- if (width >= 103) {
- g.setFont(new Font("SansSerif", Font.PLAIN, 12));
- g.drawString(logo, ip.getWidth() - 102, ip.getHeight() - 3);
- }
- } else if (width <= 300) {
- g.setFont(new Font("SansSerif", Font.BOLD, 14));
- g.drawString(logo, ip.getWidth() - 127, ip.getHeight() - 8);
- } else {
- g.setFont(new Font("SansSerif", Font.BOLD, 16));
- g.drawString(logo, ip.getWidth() - 145, ip.getHeight() - 8);
- }
- g.dispose();
- JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
- JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
- param.setQuality(0.885f, true);
- encoder.encode(bi, param);
- } catch (Exception e) {
- System.out.println("saveToFile(),保存文件失败,e: ");
- e.printStackTrace();
- } finally {
- if (fos != null) {
- try {
- fos.close();
- } catch (Exception eeee) {
- }
- }
- }
- } // end of method
- /**
- * 判断图片是否已经被处理,如果已经处理,则直接读取本地图片
- * @param imgurl
- * @return
- */
- public static boolean getRelation(String imgurl) {
- boolean state = true;
- try {
- if (SqlHelper.ifExist(imgurl)) {
- state = false;
- }
- } catch (Exception ee) {
- System.out.println("ImageTool,getRelation(): " + ee);
- }
- return state;
- }
- /**
- * 判断url地址是否合法
- * @param url
- * @return
- */
- private static boolean judgeUrl(String url) {
- boolean state = false;
- if (url.startsWith("http://")) {
- int ascii = 0;
- char data[] = url.toCharArray();
- for (int i = 0; i < data.length; i++) {
- ascii = (int) data[i];
- if (ascii > 128) {
- state = true;
- break;
- }
- }
- } else {
- state = true;
- }
- return state;
- }
- }
- java实现方便、快捷的图片编辑
- TinyXML实现快捷方便的XML文件读写
- MOSH 快捷方便的mobile shell
- 使用git快捷方便的保存代码
- JAVA原始的导出excel文件,快捷通用 方便 还可以导出word文档哦
- Flex & Java Servlet 实现简单图片编辑
- redis和spring集成(注解实现,方便,快捷)
- redis和spring集成(注解实现,方便,快捷)
- 图片背景编辑框的实现
- Java 使用SSH框架开发Jsp 方便,快捷,简单
- Linux命令行下编辑常用的快捷
- 用java代码写的图片轮播,方便调用
- DateTime JodaTime 快捷方便
- vs 2005的GridView 编辑功能实现 方便和我一样的人
- 我常用的Eclipse快捷键,方便编辑
- 一些方便的LaTex在线编辑工具
- 不用一个一个分区的整理磁盘,十分快捷方便。
- 快捷操作更方便的使用Fedora 1
- 居民用户智能抄表系统工程实施方案
- 数据库的设计决定了性能,sql server2000操作几十个G的数据很平常.
- Calculate the biggest sum of subarray
- 用eclipse调试struts时报错org.apache.struts.config.FormBeanConfig.createActionForm(FormBeanConfig.java:289)
- 基于Java的Ajax框架之JSON-RPC(三)
- java实现方便、快捷的图片编辑
- Java打印程序设计全攻略
- 什么是操作系统
- (转帖)CPU 测速(MHz)和高精度延时(微秒级)
- C ++ 动态单链表 代码
- PHP+Ajax处理JSON字符串
- 路人甲
- 开机系统启动时自动打开小键盘灯
- 很好的用的数据BUFFER,值得我们大力推广