java实现方便、快捷的图片编辑
2008-11-25 14:12
302 查看
在现在的开发中,图片的表现形式也是越来越多,随之而来的是图片的版权的问题,所以,不少的网站将自己的图片在上传的时候,打上专有的水印(如左图)。而作为图片的预览,需要有对应的适合大小的缩略图。以前在写一个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;
}
}
首先,下载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;
}
}
相关文章推荐
- 前端js实现粘贴图片到可编辑的div(其他标签也可)中
- java实现图片与base64字符串之间的转换
- java多文件上传plupload控件实现多图片上传(一)
- 基于SSM使用ueditor编辑框文本、图片上传功能实现
- 仿淘宝图片放大(java GUI实现)
- Ckeditor 图片自动上传,Java Applet实现
- Java实现图片去噪和灰度的类
- 使用Java实现在SQLserver中实现图片的存储
- java实现给图片添加水印
- [Java]中的HttpClient对象实现简单的爬虫,抓取妹子图片
- 图片数据Base64编解码(java实现)
- 微信 java 实现js-sdk 图片上传下载完整流程
- java 图片验证码的实现
- java代码实现从网上直接下载图片或者网页
- Java实现图片与base64位编码互相转换
- Java代码实现对图片压缩大小
- Google 以图搜图 - 相似图片搜索原理 - Java实现
- java实现图片文字识别ocr
- 实现将student中的所有信息在一个模板页上显示,格式参考课件中的图片。并实现编辑功能
- java读取图片处理实现缩放裁剪,用于个人信息中上传图片自定义头像大小