ServletFileUpload servletFileUpload = new ServletFileUpload();
FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(request);
byte[] imageDatas = null;
String imageName = null;
String imgFormatName = null;
if (fileItemIterator.hasNext())
{
FileItemStream fileStream = fileItemIterator.next();
imageName = fileStream.getName();
if (imageName == null || imageName.trim().length() == 0)
{
throw new Exception("文件名称为空");
}
imageName = imageName.toLowerCase();
if (imageName.endsWith("jpg") || imageName.endsWith("jpeg"))
{
imgFormatName = "jpg";
}
else if (imageName.endsWith("png"))
{
imgFormatName = "png";
}
else if (imageName.endsWith("gif"))
{
imgFormatName = "gif";
}
else
{
throw new Exception("只支持:jpg、png、gif三种图片");
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream inputStream = null;
try {
inputStream = fileStream.openStream();
BufferedImage bufferedImage = ImageIO.read(inputStream);
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
BufferedImage needSavedImage = bufferedImage;
if (width > 600) {
needSavedImage = org.imgscalr.Scalr.resize(bufferedImage, Method.SPEED, 600, Float.valueOf(height * (600.0f/width)).intValue(), org.imgscalr.Scalr.OP_BRIGHTER);
}
else if (height > 600) {
needSavedImage = org.imgscalr.Scalr.resize(bufferedImage, Method.SPEED, Float.valueOf(width * (600.0f/height)).intValue(), 600, org.imgscalr.Scalr.OP_BRIGHTER);
}
ImageIO.write(needSavedImage, imgFormatName, baos);
imageDatas = baos.toByteArray();
}
catch(Exception e)
{
Logger.error(e.getMessage(), e);
}
finally
{
if (inputStream != null)
{
try {
inputStream.close();
}
catch(Exception e)
{
Logger.error(e.getMessage(), e);
}
}
}
}
这是一个简单的例子:
1) 图片格式只是通过扩展名来做了个简单地过滤
2) 图片的压缩,逻辑简单,够用了,更复杂的逻辑,自个儿补充就行
3)用到了两个库:apache的common upload 以及图片工具类库 org.imgscalr.Scalr (github上有源码,自个儿搜)
0 个评论
要回复文章请先登录或注册