servlet上传图片生成缩略图为什么会变模糊
本帖最后由 freeman932 于 2013-10-08 22:58:15 编辑 代码如下,发现上传后的缩略图比原图模糊了很多
package servlet;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.imageio.ImageIO;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/** * Servlet implementation class for Servlet: UploadServlet * */
public class UploadServlet extends javax.servlet.http.HttpServlet implements
javax.servlet.Servlet {
//File tmpDir = null;// 初始化上传文件的临时存放目录
//File saveDir = null;// 初始化上传文件后的保存目录
public UploadServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@SuppressWarnings({ "unchecked", "deprecation" })
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");//设置输出编码格式
request.setCharacterEncoding("UTF-8"); //设置输入编码格式
PrintWriter out = response.getWriter();
//判断表单是否是 enctype="multipart/form-data"
if (ServletFileUpload.isMultipartContent(request)) {
DiskFileItemFactory dfif = new DiskFileItemFactory();
dfif.setSizeThreshold(5 * 1024 * 1024); // 设定使用内存超过5M时,将产生临时文件并存储于临时目录中。
dfif.setRepository(new File("f:\\download")); // 设定存储临时文件的目录。
ServletFileUpload fileupload = new ServletFileUpload(dfif);
fileupload.setSizeMax(50 * 1024 * 1024); // 设定最大允许上传50M的文件。
//List fileitems = null;
try {
/*fileitems=fileupload.parseRequest(request);
Iterator iter=fileitems.iterator();
while(iter.hasNext()){
FileItem f=(FileItem)iter.next();*/
List<FileItem> files = fileupload.parseRequest(request);//调用 ServletFileUpload 的 parseRequest() 方法, 获取 FileItem 的集合
for (FileItem f : files) {
if (f.isFormField()) {
out.print(f.getFieldName());
out.print(f.getString("UTF-8")); // 因为Web使用的是UTF-8编码,所以客户端返回的也是UTF-8的编码。
//continue;
} else {
//系统的语言 或者 jdk的 fileencoding参数 要与console一致
//out.print(f.getString("UTF-8"));
String filename = f.getName();
//filename=new String(filename.getBytes(), "ISO8859-1");
//out.println("<script>alert('"+filename+"')</script>");
String fileext = filename.substring(filename.lastIndexOf(".")); //取得拟上传文件的扩展名,lastIndexOF返回指定子字符串在此字符串中最右边出现处的索引,如果它不作为一个子字符串出现,则返回-1。
// substring返回一个新的字符串,它是此字符串的一个子字符串。该子字符串从指定索引处的字符开始,直到此字符串末尾。
//out.println("<script>alert('"+fileext+"')</script>");
if (!fileext.equalsIgnoreCase(".jpg")){//java中字符串比较不能用=或!=,要用equalsIgnoreCase
out.println("<script>alert('不正确的文件,请上传图片文件');location.href='/zgy/admin/upload.jsp';</script>");
//RequestDispatcher requestDispatcher=request.getRequestDispatcher("admin/upload.jsp");//页面跳转
//requestDispatcher.forward(request, response);
return;
}
String path = request.getSession().getServletContext().getRealPath("");//取得当前运行文件在服务器上的绝对路径,request.getRealPath("/")这个用法已经过时
//String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currentTime = new Date();
String strtime=formatter.format(currentTime).toString();
String year = strtime.substring(0,4);//strtime.length()-3,strtime.length();
String month = strtime.substring(5,7);
String day = strtime.substring(8,10);
String hour = strtime.substring(11,13);
String minute = strtime.substring(14,16);
String second = strtime.substring(17,19);
f.write(new File(path+"\\upload\\pic\" +year+month+day+hour+minute+second+ fileext));
//out.println("<script>alert('上传图片成功');</script>");//location.href='/lab/admin/upload_showfile.jsp';</script>");
//String tempfilename1="upload"+"\"+"pic"+"\"+year+month+day+hour+minute+second+ fileext;
//out.println("<script>alert('"+tempfilename+"')</script>");
//以下生成缩略图
File file2=new File(path+"\\upload\\pic\" +year+month+day+hour+minute+second+ fileext);
Image src=ImageIO.read(file2);
int new_w=450;
int new_h=300;
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(path+"\\upload\\pic\"+year+month+day+hour+minute+second+"_min"+fileext);
String tempfilename="upload"+"\\\"+"pic"+"\\\"+year+month+day+hour+minute+second+ "_min"+fileext;//要用四个\\\\才能转义一个\
request.getSession().setAttribute("uploadfilename",tempfilename);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
encoder.encode(tag);//近JPEG编码
newimage.close();
//returnflag = 1;
RequestDispatcher requestDispatcher=request.getRequestDispatcher("admin/upload_showfile.jsp");//页面跳转
requestDispatcher.forward(request, response);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
out.print("你所提交的表单有错误!");
}
}
}
[解决办法]
ImageIO.write(ChartImage, "jpeg", out);