使用SmartUplaod实现图片上传,并给上传图片添加水印后将请求参数以对象的方式返回

6 篇文章 0 订阅
 package com.yc.smartupload.util;


import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.jsp.PageContext;

import com.jspsmart.upload.File;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;

/**
 * 图片上传的工具类
 * @author navy
 */
@SuppressWarnings("unchecked")
public class FileUploadUtil {
public static String PATH="../pics";//文件上传的路径  与项目平级 在项目部署时不会清空  /表示在server的项目级
//private static final String ALLOWED="gif,jpg,jpeg,png,doc,txt,xls,ico";//允许上传文件类型
private static final String DENIED="exe,bat,jsp,html,com";//不允许上传的文件类型
private static final int SINGLEFILESIZE=1024*1024;//单个文件最大大小
private static final int TOTALMAXSIZE=20*1024*1024;//每次上传总文件大小

/**
 * 将请求转成一个对象,并给上传的图片添加水印
 * @param pageContext
 * @param c
 * @return
 * @throws Exception
 */
public <T> T uploadToObjectAndSetWaterImage(PageContext pageContext,Class<T> c) throws Exception{
//实例化一个SmartUpload对象
SmartUpload su = new SmartUpload();//文件上传包的使用
//初始化SmartUpload
su.initialize(pageContext);
//设置参数
//su.setAllowedFilesList(ALLOWED);
su.setDeniedFilesList(DENIED);
su.setMaxFileSize(SINGLEFILESIZE);
su.setTotalMaxFileSize(TOTALMAXSIZE);
su.setCharset("utf-8");

//开始上传
su.upload();
//获取转换后的请求
Request request = su.getRequest();


T t=c.newInstance(); //此时调用的是给定类的无参构造方法  StoreType.class   new  StoreType()

//获取请求中的所有数据
Enumeration<String> names=request.getParameterNames(); //获取请求中的数据的所有的键,即input标签中name属性的属性值
//tname setTname()  跟对应的对象中的方法去比较

//获取给定对象中的所有setter方法
Method[] methods=c.getMethods();

List<Method> list=new ArrayList<Method>();

//提取setter方法
for(Method method:methods){
if(method.getName().startsWith("set")){
list.add(method);
}
}

//循环取出每一个表单元素名已对一的值 村到map中
String fieldName=null;
String fieldNameSetter=null;
String typeName=null; 
while(names.hasMoreElements()){
fieldName=names.nextElement(); //获取提交的表单中的表单元素名
fieldNameSetter="set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
for(Method method:list){
if(fieldNameSetter.equals(method.getName())){
try {
typeName=method.getParameterTypes()[0].getSimpleName();
if("int".equals(typeName) || "Integer".equals(typeName)){
method.invoke(t,Integer.parseInt(request.getParameter(fieldName).trim()));
}else if("double".equals(typeName) || "float".equals(typeName) || "Double".equals(typeName) || "Float".equals(typeName)){
method.invoke(t,Double.parseDouble(request.getParameter(fieldName).trim()));
}else{
method.invoke(t,request.getParameter(fieldName).trim());
}
} catch (Exception e) {
e.printStackTrace();
}
break;//如果找到了,则进行下一次循环
}
}
}

//将上传文件存到服务器路径下
Files files = su.getFiles();
if(files!=null && files.getCount()>0){//说明用户文件已传上来
String path = null;//文件保存路径
String fileName =null;//文件名
String temp="";
String oldFieldName="";
String ext=null; //后缀

Collection<File> collection = files.getCollection();
path=pageContext.getServletContext().getRealPath("/")+PATH;

for(File fl:collection){//循环取出每一个上传文件
if(!fl.isMissing()){//文件没有丢失
fieldName = fl.getFieldName();//license  pic   pic
if("".equals(oldFieldName)){
oldFieldName=fieldName;
}else{
if(!oldFieldName.equals(fieldName)){ //说明不是同一个文本框中的图片
if(!"".equals(temp)){
//图片上传完成后,将路径存入到对象的对应属性中
fieldNameSetter="set"+oldFieldName.substring(0,1).toUpperCase()+oldFieldName.substring(1);
for(Method method:list){
if(fieldNameSetter.equals(method.getName())){
method.invoke(t,temp);
}
}
}
temp="";
oldFieldName=fieldName;
}
}
ext=fl.getFileExt();
fileName = new Date().getTime()+"_"+new Random().nextInt(10000)+"."+ext;
//保存数据到指定文件
fl.saveAs(path+"/"+fileName);

if(ext.equalsIgnoreCase("png") || ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("gif")){
//给图片添加水印
fileName=ImageWaterMarkUtil.waterMarkImage(path+"/"+fileName,fileName);
}
if(!"".equals(temp)){
temp+=",";
}
temp+=fileName;
}
}

if(!"".equals(temp)){
//图片上传完成后,将路径存入到对象的对应属性中
fieldNameSetter="set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
for(Method method:list){
if(fieldNameSetter.equals(method.getName())){
method.invoke(t,temp);
}
}
}
}

return t;
}
}


package com.yc.smartupload.util;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 图片水印
 * @author navy
 */
public class ImageWaterMarkUtil {
public static String realPath; //服务器的绝对路径
public static String uploadPath; //图片上传后的相对服务器路径
public static String logoPath; //水印图片路径
private static int waterImageWidth=0; //水印图片的宽度
private static int waterImageHeight=0; //水印图片高度
private static Image imageLogo; //水印图片
/**
 * 获取水印图片信息
 */
public static void init(){
try {
//(1)获取水印图片
File logo=new File(logoPath);
//(2)获取水印图片的大小
imageLogo=ImageIO.read(logo);
waterImageWidth=imageLogo.getWidth(null);
waterImageHeight=imageLogo.getHeight(null);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
 * 给指定的图片添加水印
 * @param picPath 要添加水印的图片的绝对路径
 * @param fileName 要添加水印的图片的文件名
 * @return 添加水印后的图片路径
 */
public static String waterMarkImage(String picPath,String fileName){
FileOutputStream fos=null;
try {
File pic=new File(picPath);
Image image=ImageIO.read(pic); //获取要添加水印的图片信息
int width=image.getWidth(null);//获取要添加水印的图片的宽度
int height=image.getHeight(null);//获取要添加水印的图片的高度
//1.创建一个图片缓存对象  对宽度  高度和颜色进行设置和调整  
BufferedImage bufferedImage=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//2.创建java绘图工具对象
Graphics2D gp=bufferedImage.createGraphics();
//3.使用绘图工具对象将原图绘制到缓冲图片区
gp.drawImage(image,0,0,width,height,null);
//4.设置水印图片的透明图
gp.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,(float)0.8));
//5.计算水印图片的位置
int x=width-waterImageWidth;
int y=height-waterImageHeight;
//6.绘制水印图片
gp.drawImage(imageLogo,x,y,null);
//7.释放工具
gp.dispose();
//8.将图片写入到指定的文件中
fileName="YC_"+fileName;
fos=new FileOutputStream(realPath+"/"+fileName);
JPEGImageEncoder jie=JPEGCodec.createJPEGEncoder(fos);
jie.encode(bufferedImage);
} catch (IOException e) {
e.printStackTrace();
} finally{
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//返回添加水印的图片在服务器中的路径
return uploadPath+"/"+fileName;
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值