jsp中上传图片

有关FileUpload组件的使用和调试的经验:
在通过使用FileUpload组件上传的过程中,通过自己的调试,总结如下:
1)使用之前的准备,我用的是commons-fileupload-1.1-dev.jar和commons-io-1.1-dev.jar
jsp 上传图片并生成缩位图或者加水印
有些网站 动网, 上传图片后加给加上自己的字(是在图片上加的)

 请问在JSP里如何实现??
//添加水印,filePath 源图片路径, watermark 水印图片路径
public static boolean createMark(String filePath,String watermark) {
ImageIcon imgIcon=new ImageIcon(filePath);
Image theImg =imgIcon.getImage();
ImageIcon waterIcon=new ImageIcon(watermark);
Image waterImg =waterIcon.getImage();
int width=theImg.getWidth(null);
int height= theImg.getHeight(null);
BufferedImage bimage = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
Graphics2D g=bimage.creatGraphics( );
g.setColor(Color.red);
g.setBackground(Color.white);
g.drawImage(theImg, 0, 0, null );
g.drawImage(waterImg, 100, 100, null );
g.drawString("12233",10,10); //添加文字
g.dispose();
try{
FileOutputStream out=new FileOutputStream(filePath);
JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
param.setQuality(50f, true);
encoder.encode(bimage, param);
out.close();
}catch(Exception e){ return false; }
return true;
}



2005-7-12



生成水印图片的java程序

import java.io.File;
import java.io.FileOutputStream;
import java.awt.Image;
import java.awt.image.BufferedImage;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
* 生成水印图片
*/
public class Watermark{

public static void thumbPic(String filename) {
try {
File file = new File(filename);
Image src = javax.imageio.ImageIO.read(file);
File file_sy = new File("D:\\test\\ico.gif");
Image src_sy = javax.imageio.ImageIO.read(file_sy);
int width = src.getWidth(null);
int height = src.getHeight(null);
int new_width = 0;
int new_height = 0;
if (width >= height) {
new_width = 600;
} else {
new_width = 600;
}
new_height = ( (new_width * height) / width);
BufferedImage tag = new BufferedImage(new_width, new_height, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src, 0, 0, new_width, new_height, null);
tag.getGraphics().drawImage(src_sy, new_width - src_sy.getWidth(null), new_height - src_sy.getHeight(null), 98, 40, null);
FileOutputStream out = new FileOutputStream(filename + "_thumb.jpg");
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
} catch (Exception e) {
System.out.println(e);
}
}

public static void main(String args[]) {
JPG.thumbPic("D:\\test\\source.jpg"

);
}

}



/////////////////范例////////////////////
package package;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

public class upload
{

private static String newline = "\n";
private String uploadDirectory;
private String ContentType;
private String CharacterEncoding;

public upload()
{
uploadDirectory = ".";
ContentType = "";
CharacterEncoding = "";
}

private String getFileName(String s)
{
int i = https://www.360docs.net/doc/318864652.html,stIndexOf("\\");
if(i < 0 || i >= s.length() - 1)
{
i = https://www.360docs.net/doc/318864652.html,stIndexOf("/");
if(i < 0 || i >= s.length() - 1)
return s;
}
return s.substring(i + 1);
}

public void setUploadDirectory(String s)
{
uploadDirectory = s;
}

public void setContentType(String s)
{
ContentType = s;
int i;
if((i = ContentType.indexOf("boundary=")) != -1)
{
ContentType = ContentType.substring(i + 9);
ContentType = "--" + ContentType;
}
}

public void setCharacterEncoding(String s)
{
CharacterEncoding = s;
}

public String uploadFile(HttpServletRequest httpservletrequest)
throws ServletException, IOException
{
String s = null;
setCharacterEncoding(httpservletrequest.getCharacterEncoding());
setContentType(httpservletrequest.getContentType());
s = uploadFile(httpservletrequest.getInputStream());
return s;
}

public String uploadFile(ServletInputStream servletinputstream)
throws ServletException, IOException
{
String s = null;
String s1 = null;
byte abyte0[] = new byte[4096];
byte abyte1[] = new byte[4096];
int ai[] = new int[1];
int ai1[] = new int[1];
String s2;
while((s2 = readLine(abyte0, ai, servletinputstream, CharacterEncoding)) != null)
{
int i = s2.indexOf("filename=");
if(i >= 0)
{
s2 = s2.substring(i + 10);
if((i = s2.indexOf("\"")) > 0)
s2 = s2.substring(0, i);
break;
}
}
s1 = s2;
if(s1 != null && !s1.equals("\""))
{
s1 = getFileName(s1);
String s3 = readLine(abyte0, ai, servletinputstream, CharacterEncoding);
if(s3.indexOf("Content-Type") >= 0)
readLine(abyte0, ai, servletinputstream, CharacterEncoding);
File file = new File(uploadDirectory, s1);
FileOutputStream fileoutputstream = new FileOutputStream(file);
while((s3 = readLine(abyte0, ai, servletinputstream, CharacterEncoding)) != null)
{
if(s3.indexOf(ContentType) == 0 && abyte0[0] == 45)
break;
if(s != null)
{
fileoutputstream.write(abyte1, 0, ai1[0]);
fileoutputstream.flush();
}
s = readLine(abyte1, ai1, servletinputstream, CharacterEncoding);
if(s == null || s.indexOf(ContentType) == 0 && abyte1[0] == 45)
break;
fileoutputstream.write(abyte0, 0, ai[0]);
fileoutputstream.flush();
}
byte byte0;
if(newline.length() == 1)
byte0 = 2;
else
byte0 = 1;
if(s != null && abyte1[0] != 45 && ai1[0] > newline.length() * byte0)
fileoutputstream.write(abyte1, 0, ai1[0] - newline.length() * byte0);
if(s3 != null && abyte0[0] != 45 && ai[0] > newline.length() * byte0)
fileoutputstream.write(aby

te0, 0, ai[0] - newline.length() * byte0);
fileoutputstream.close();
}
return s1;
}

private String readLine(byte abyte0[], int ai[], ServletInputStream servletinputstream, String s)
{
ai[0] = servletinputstream.readLine(abyte0, 0, abyte0.length);
if(ai[0] == -1)
return null;
break MISSING_BLOCK_LABEL_27;
Object obj;
obj;
return null;
if(s == null)
return new String(abyte0, 0, ai[0]);
return new String(abyte0, 0, ai[0], s);
obj;
return null;
}

}


JSP页:

<%@page contentType="text/html;charset=gb2312" import="package.upload"%>
<%
String Dir = "c:\dir\upload";
String fn="";
upload upload = new upload();
upload.setUploadDirectory(Dir);
fn=upload.uploadFile(request);
%>

随机图片名称
<%
mySmartUpload.initialize(pageContext);
mySmartUpload.service(request,response);
mySmartUpload.upload();
String fn=mySmartUpload.getFiles().getFile(0).getFileName();
mySmartUpload.save("upload/"); //文件保存的目录为upload
out.println("已经成功上传了文件,请查看这里");
%>
上面的程序可以上传图片,不过只能上传gif或者JPG图片。
而且保存图片在upload文件夹下面,要想GIF或Jpg图片的名称变为年+月+日+随机数.gif或年+月+日+随机数.jpg
只允许上传jpg或gif图片,在客户端用javaScript控制要好些。
变图片名称可用如下代码:自己看看就明白了。:
//得到实际路径

String realPath = this.masRequest.getRequest().getRealPath("/");
String userPhotoPath = realPath + "images\\UserPhoto\\";
userPhotoPath = MasString.replace(userPhotoPath,"\\","\\\\");
if (!file.getFileName().trim().equals(""))
{
//根据系统时间生成文件名
Date nowTime = new Date();
emp_Photo = userPhotoPath + String.valueOf(nowTime.getTime()) +"."+ file.getFileExt();
file.saveAs(emp_Photo);
System.out.println("file.saveAs() = " + "OK!!!");
}
************************************************
************************************************
************************************************
************************************************
************************************************
************************************************
************************************************
JSP上传图片并生成缩略图

本例子使用了jspsmart组件进行上传,这里可以免费下载该组件https://www.360docs.net/doc/318864652.html,
下载解压后,将jar包复制到 \WEB-INF\lib 目录后重启服务器,jspsmart即可正常使用了

1、uploadimage.jsp

<%@ page contentType="text/html;charset=gb2312" language="java" import="java.io.*,java.awt.Image,java.awt.image.*,com.sun.image.codec.jpeg.*,java.sql.*,com.jspsmart.upload.*,java.util.*,cn.oof.database.*,cn.oof.house.*"%>
<%
SmartUpload mySmartUpload =new SmartUpload();
long file_size_max=4000000;
String fileName2="",ext="",testvar="";
String url="uploadfile/images/"; //应保证在根目录中有此目录的存在
//初始化
mySmartUplo

ad.initialize(pageContext);
//只允许上载此类文件
try {
mySmartUpload.setAllowedFilesList("jpg,gif");
//上载文件
mySmartUpload.upload();
} catch (Exception e){
%>

<%
}
try{

com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
if (myFile.isMissing()){%>

<%}
else{
//String myFileName=myFile.getFileName(); //取得上载的文件的文件名
ext= myFile.getFileExt(); //取得后缀名
int file_size=myFile.getSize(); //取得文件的大小
String saveurl="";
if(file_size//更改文件名,取得当前上传时间的毫秒数值
Calendar calendar = Calendar.getInstance();
String filename = String.valueOf(calendar.getTimeInMillis());
saveurl=request.getRealPath("/")+url;
saveurl+=filename+"."+ext; //保存路径
myFile.saveAs(saveurl,mySmartUpload.SAVE_PHYSICAL);
//out.print(filename);
//-----------------------上传完成,开始生成缩略图-------------------------
java.io.File file = new java.io.File(saveurl); //读入刚才上传的文件
String newurl=request.getRealPath("/")+url+filename+"_min."+ext; //新的缩略图保存地址
Image src = javax.imageio.ImageIO.read(file); //构造Image对象
float tagsize=200;
int old_w=src.getWidth(null); //得到源图宽
int old_h=src.getHeight(null);
int new_w=0;
int new_h=0; //得到源图长
int tempsize;
float tempdouble;
if(old_w>old_h){
tempdouble=old_w/tagsize;
}else{
tempdouble=old_h/tagsize;
}
new_w=Math.round(old_w/tempdouble);
new_h=Math.round(old_h/tempdouble);//计算新图长宽
BufferedImage tag = new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); //绘制缩小后的图
FileOutputStream newimage=new FileOutputStream(newurl); //输出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
encoder.encode(tag); //近JPEG编码
newimage.close();

}
else{
out.print("");
}
}
}catch (Exception e){

e.toString();

}
%>

2 upload.htm


请选择上传的图片






ight="45" align="center" valign="middle">


请选择上传的图片






************************************************
************************************************
************************************************
************************************************
************************************************
************************************************
************************************************


相关文档
最新文档