package util;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class ScaleImage {
private int width;
private int height;
private int scaleWidth;
double support = (double) 3.0;
double PI = (double) 3.14159265358978;
double[] contrib;
double[] normContrib;
double[] tmpContrib;
int startContrib, stopContrib;
int nDots;
int nHalfDots;
public void suoImage(File file2,String savaurl) throws Exception
{
java.io.File file = file2;
Image src = javax.imageio.ImageIO.read(file);
float tagsize=160;
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(savaurl);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
encoder.encode(tag);
newimage.close();
}
// fromFileStr原图片地�?,saveToFileStr生成缩略图地�?,formatWideth生成图片宽度,formatHeight高度
public void saveImageAsJpg(String fromFileStr, String saveToFileStr,
int formatWideth, int formatHeight) throws Exception {
BufferedImage srcImage;
File saveFile = new File(saveToFileStr);
File fromFile = new File(fromFileStr);
srcImage = javax.imageio.ImageIO.read(fromFile); // construct image
int imageWideth = srcImage.getWidth(null);
int imageHeight = srcImage.getHeight(null);
int changeToWideth = 0;
int changeToHeight = 0;
if (imageWideth > 0 && imageHeight > 0) {
// flag=true;
if (imageWideth / imageHeight >= formatWideth / formatHeight) {
if (imageWideth > formatWideth) {
changeToWideth = formatWideth;
changeToHeight = (imageHeight * formatWideth) / imageWideth;
} else {
changeToWideth = imageWideth;
changeToHeight = imageHeight;
}
} else {
if (imageHeight > formatHeight) {
changeToHeight = formatHeight;
changeToWideth = (imageWideth * formatHeight) / imageHeight;
} else {
changeToWideth = imageWideth;
changeToHeight = imageHeight;
}
}
}
srcImage = imageZoomOut(srcImage, changeToWideth, changeToHeight);
ImageIO.write(srcImage, "JPEG", saveFile);
}
public BufferedImage imageZoomOut(BufferedImage srcBufferImage, int w, int h) {
width = srcBufferImage.getWidth();
height = srcBufferImage.getHeight();
scaleWidth = w;
if (DetermineResultSize(w, h) == 1) {
return srcBufferImage;
}
CalContrib();
BufferedImage pbOut = HorizontalFiltering(srcBufferImage, w);
BufferedImage pbFinalOut = VerticalFiltering(pbOut, h);
return pbFinalOut;
}
// 决定图片尺寸
private int DetermineResultSize(int w, int h) {
double scaleH, scaleV;
scaleH = (double) w / (double) width;
scaleV = (double) h / (double) height;
// �?要判断一下scaleH,scaleV,不做放大操�?
if (scaleH >= 1.0 && scaleV >= 1.0) {
return 1;
}
return 0;
} // end of DetermineResultSize()
private double Lanczos(int i, int inWidth, int outWidth, double Support) {
double x;
x = (double) i * (double) outWidth / (double) inWidth;
return Math.sin(x * PI) / (x * PI) * Math.sin(x * PI / Support)
/ (x * PI / Support);
}
private void CalContrib() {
nHalfDots = (int) ((double) width * support / (double) scaleWidth);
nDots = nHalfDots * 2 + 1;
try {
contrib = new double[nDots];
normContrib = new double[nDots];
tmpContrib = new double[nDots];
} catch (Exception e) {
System.out.println("init contrib,normContrib,tmpContrib" + e);
}
int center = nHalfDots;
contrib[center] = 1.0;
double weight = 0.0;
int i = 0;
for (i = 1; i <= center; i++) {
contrib[center + i] = Lanczos(i, width, scaleWidth, support);
weight += contrib[center + i];
}
for (i = center - 1; i >= 0; i--) {
contrib[i] = contrib[center * 2 - i];
}
weight = weight * 2 + 1.0;
for (i = 0; i <= center; i++) {
normContrib[i] = contrib[i] / weight;
}
for (i = center + 1; i < nDots; i++) {
normContrib[i] = normContrib[center * 2 - i];
}
} // end of CalContrib()
// 处理边缘
private void CalTempContrib(int start, int stop) {
double weight = 0;
int i = 0;
for (i = start; i <= stop; i++) {
weight += contrib[i];
}
for (i = start; i <= stop; i++) {
tmpContrib[i] = contrib[i] / weight;
}
} // end of CalTempContrib()
private int GetRedValue(int rgbValue) {
int temp = rgbValue & 0x00ff0000;
return temp >> 16;
}
private int GetGreenValue(int rgbValue) {
int temp = rgbValue & 0x0000ff00;
return temp >> 8;
}
private int GetBlueValue(int rgbValue) {
return rgbValue & 0x000000ff;
}
private int ComRGB(int redValue, int greenValue, int blueValue) {
return (redValue << 16) + (greenValue << 8) + blueValue;
}
// 行水平滤�?
private int HorizontalFilter(BufferedImage bufImg, int startX, int stopX,
int start, int stop, int y, double[] pContrib) {
double valueRed = 0.0;
double valueGreen = 0.0;
double valueBlue = 0.0;
int valueRGB = 0;
int i, j;
for (i = startX, j = start; i <= stopX; i++, j++) {
valueRGB = bufImg.getRGB(i, y);
valueRed += GetRedValue(valueRGB) * pContrib[j];
valueGreen += GetGreenValue(valueRGB) * pContrib[j];
valueBlue += GetBlueValue(valueRGB) * pContrib[j];
}
valueRGB = ComRGB(Clip((int) valueRed), Clip((int) valueGreen),
Clip((int) valueBlue));
return valueRGB;
} // end of HorizontalFilter()
// 图片水平滤波
private BufferedImage HorizontalFiltering(BufferedImage bufImage, int iOutW) {
int dwInW = bufImage.getWidth();
int dwInH = bufImage.getHeight();
int value = 0;
BufferedImage pbOut = new BufferedImage(iOutW, dwInH,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < iOutW; x++) {
int startX;
int start;
int X = (int) (((double) x) * ((double) dwInW) / ((double) iOutW) + 0.5);
int y = 0;
startX = X - nHalfDots;
if (startX < 0) {
startX = 0;
start = nHalfDots - X;
} else {
start = 0;
}
int stop;
int stopX = X + nHalfDots;
if (stopX > (dwInW - 1)) {
stopX = dwInW - 1;
stop = nHalfDots + (dwInW - 1 - X);
} else {
stop = nHalfDots * 2;
}
if (start > 0 || stop < nDots - 1) {
CalTempContrib(start, stop);
for (y = 0; y < dwInH; y++) {
value = HorizontalFilter(bufImage, startX, stopX, start,
stop, y, tmpContrib);
pbOut.setRGB(x, y, value);
}
} else {
for (y = 0; y < dwInH; y++) {
value = HorizontalFilter(bufImage, startX, stopX, start,
stop, y, normContrib);
pbOut.setRGB(x, y, value);
}
}
}
return pbOut;
} // end of HorizontalFiltering()
private int VerticalFilter(BufferedImage pbInImage, int startY, int stopY,
int start, int stop, int x, double[] pContrib) {
double valueRed = 0.0;
double valueGreen = 0.0;
double valueBlue = 0.0;
int valueRGB = 0;
int i, j;
for (i = startY, j = start; i <= stopY; i++, j++) {
valueRGB = pbInImage.getRGB(x, i);
valueRed += GetRedValue(valueRGB) * pContrib[j];
valueGreen += GetGreenValue(valueRGB) * pContrib[j];
valueBlue += GetBlueValue(valueRGB) * pContrib[j];
}
valueRGB = ComRGB(Clip((int) valueRed), Clip((int) valueGreen),
Clip((int) valueBlue));
return valueRGB;
} // end of VerticalFilter()
private BufferedImage VerticalFiltering(BufferedImage pbImage, int iOutH) {
int iW = pbImage.getWidth();
int iH = pbImage.getHeight();
int value = 0;
BufferedImage pbOut = new BufferedImage(iW, iOutH,
BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < iOutH; y++) {
int startY;
int start;
int Y = (int) (((double) y) * ((double) iH) / ((double) iOutH) + 0.5);
startY = Y - nHalfDots;
if (startY < 0) {
startY = 0;
start = nHalfDots - Y;
} else {
start = 0;
}
int stop;
int stopY = Y + nHalfDots;
if (stopY > (int) (iH - 1)) {
stopY = iH - 1;
stop = nHalfDots + (iH - 1 - Y);
} else {
stop = nHalfDots * 2;
}
if (start > 0 || stop < nDots - 1) {
CalTempContrib(start, stop);
for (int x = 0; x < iW; x++) {
value = VerticalFilter(pbImage, startY, stopY, start, stop,
x, tmpContrib);
pbOut.setRGB(x, y, value);
}
} else {
for (int x = 0; x < iW; x++) {
value = VerticalFilter(pbImage, startY, stopY, start, stop,
x, normContrib);
pbOut.setRGB(x, y, value);
}
}
}
return pbOut;
} // end of VerticalFiltering()
int Clip(int x) {
if (x < 0)
return 0;
if (x > 255)
return 255;
return x;
}
}
package servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
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 util.ScaleImage;
public class FileUpload extends HttpServlet {
private static int formatWideth = 200;// 生成缩略图的宽
private static int formatHeight = 200;// 生成缩略图的高
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//request.setCharacterEncoding("utf-8"); // 设置编码
response.setContentType("text/html; charset=utf-8");
response.setCharacterEncoding("utf-8");// 设置编码
// 获得磁盘文件条目工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
// 获取文件需要上传到的路径
String path = request.getRealPath("/upload");
// 如果没以下两行设置的话,上传大的 文件 会占用 很多内存,
// 设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同
/**
* 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上, 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem
* 格式的 然后再将其真正写到 对应目录的硬盘上
*/
factory.setRepository(new File(path));
// 设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
factory.setSizeThreshold(1024 * 1024);
// 高水平的API文件上传处理
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// 可以上传多个文件
List<FileItem> list = (List<FileItem>) upload.parseRequest(request);
for (FileItem item : list) {
// 获取表单的属性名字
String name = item.getFieldName();
// 如果获取的 表单信息是普通的 文本 信息
if (item.isFormField()) {
// 获取用户具体输入的字符串
String value = item.getString();
value = new String(value.getBytes("ISO-8859-1"),"utf-8");
request.setAttribute(name, value);
}
// 对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些
else {
// 获取路径名
String value = item.getName();
// 索引到最后一个反斜杠
int start = value.lastIndexOf("\\");
// 截取 上传文件的 字符串名字,加1是 去掉反斜杠,
String filename = value.substring(start + 1);
request.setAttribute(name, filename);
OutputStream out = new FileOutputStream(new File(path, filename));
InputStream in = item.getInputStream();
int length = 0;
byte[] buf = new byte[1024];
System.out.println("获取上传文件的总共的容量:" + item.getSize());
// in.read(buf) 每次读到的数据存放在 buf 数组中
while ((length = in.read(buf)) != -1) {
// 在 buf 数组中 取出数据 写到 (输出流)磁盘上
out.write(buf, 0, length);
}
in.close();
out.close();
ScaleImage si = new ScaleImage();
//String filenameNew = filename.substring(0,filename.lastIndexOf("."));//缩略图名
//String ext = filename.substring(filename.lastIndexOf(".")); //缩略图扩展名
//si.saveImageAsJpg(path+"\\"+filename, path+"\\small\\"+filenameNew+ext, formatWideth, formatHeight);
si.saveImageAsJpg(path+"\\"+filename, path+"\\small\\"+filename, formatWideth, formatHeight);
request.setAttribute("smallName", filename);
}
}
} catch (Exception e) {
e.printStackTrace();
}
request.getRequestDispatcher("filedemo.jsp").forward(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
index.jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'fileupload.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="FileUpload" enctype="multipart/form-data" method="post" >
用户名:<input type="text" name="usename"> <br/>
上传文件:<input type="file" name="file1"><br/>
<!--
上传文件: <input type="file" name="file2"><br/>
-->
<input type="submit" value="提交"/>
</form>
</body>
</html>
filedemo.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'filedemo.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
用户名:${requestScope.usename } <br/>
文件:${requestScope.file1 }<br/>
${requestScope.file2 }<br/>
<!-- 把上传的图片显示出来 -->
<img alt="go" src="upload/small/<%=(String)request.getAttribute("file1")%> " />
<br><br><br><br><br>
<img alt="go" src="upload/<%=(String)request.getAttribute("file1")%> " />
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>FileUpload</servlet-name>
<servlet-class>servlet.FileUpload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUpload</servlet-name>
<url-pattern>/FileUpload</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
源码http://download.csdn.net/detail/djun100/5994569