本文参考传智播客巴巴运动网视频教程
构建保存图片的路径:
String pathdir = "/images/product/"+ productTypeId+ "/"+ productId+ "/prototype";//构建文件保存的目录
为什么要有那么多个目录,因为java本身不会去获取图片,而是调用了操作系统的一些接口来获取图片,如果一个目录下图片太多的话,操作系统获取图片的速度会变慢
,所以巴巴运动网在构建图片路径的时候搞了多个目录,分散保存图片。
有了这个pathdir就可以得到图片保存目录的真实路径:
String realpathdir = request.getSession().getServletContext().getRealPath(pathdir);
获取了图片的真实路径后,就可以开始保存图片了:
File savedir = new File(realpathdir);
File file = saveFile(savedir, filename, imagefile.getFileData());
imagefile为struts的FormFile类的对象,
filename为文件名,这两个属性都可以从前台获取过来。以下是saveFile方法的代码:
/**
* 保存文件
* @param savedir 存放目录
* @param fileName 文件名称
* @param data 保存的内容
* @return 保存的文件
* @throws Exception
*/
public static File saveFile(File savedir, String fileName, byte[] data) throws Exception{
if(!savedir.exists()) savedir.mkdirs();//如果目录不存在就创建
File file = new File(savedir, fileName);
FileOutputStream fileoutstream = new FileOutputStream(file);
fileoutstream.write(data);
fileoutstream.close();
return file;
}
保存完图片后还要保存一张图片的缩略图,宽度为140px
String pathdir140 = "/images/product/"+ productTypeId+ "/"+ productId+ "/140x";//140宽度的图片保存目录
String realpathdir140 = request.getSession().getServletContext().getRealPath(pathdir140);
File savedir140 = new File(realpathdir140);
if(!savedir140.exists()) savedir140.mkdirs();//如果目录不存在就创建
File file140 = new File(realpathdir140, filename);
ImageSizer.resize(file, file140, 140, ext);
这里我们用到了一个从网上下的用于压缩图片的ImageSizer工具类的静态方法,resize方法传进去的四个参数分别代表原始图片对象,需要被压缩的图片对象,压缩宽度的大小,图片后缀名。这个工具类只能压缩jpg, png, gif(非动画)三种格式,如果想压缩更多的格式需要付费。以下是该工具类:
/**
* 图像压缩工具
* @author lihuoming@sohu.com
*
*/
public class ImageSizer {
public static final MediaTracker tracker = new MediaTracker(new Component() {
private static final long serialVersionUID = 1234162663955668507L;}
);
/**
* @param originalFile 原图像
* @param resizedFile 压缩后的图像
* @param width 图像宽
* @param format 图片格式 jpg, png, gif(非动画)
* @throws IOException
*/
public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException {
if(format!=null && "gif".equals(format.toLowerCase())){
resize(originalFile, resizedFile, width, 1);
return;
}
FileInputStream fis = new FileInputStream(originalFile);
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
int readLength = -1;
int bufferSize = 1024;
byte bytes[] = new byte[bufferSize];
while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) {
byteStream.write(bytes, 0, readLength);
}
byte[] in = byteStream.toByteArray();
fis.close();
byteStream.close();
Image inputImage = Toolkit.getDefaultToolkit().createImage( in );
waitForImage( inputImage );
int imageWidth = inputImage.getWidth( null );
if ( imageWidth < 1 )
throw new IllegalArgumentException( "image width " + imageWidth + " is out of range" );
int imageHeight = inputImage.getHeight( null );
if ( imageHeight < 1 )
throw new IllegalArgumentException( "image height " + imageHeight + " is out of range" );
// Create output image.
int height = -1;
double scaleW = (double) imageWidth / (double) width;
double scaleY = (double) imageHeight / (double) height;
if (scaleW >= 0 && scaleY >=0) {
if (scaleW > scaleY) {
height = -1;
} else {
width = -1;
}
}
Image outputImage = inputImage.getScaledInstance( width, height, java.awt.Image.SCALE_DEFAULT);
checkImage( outputImage );
encode(new FileOutputStream(resizedFile), outputImage, format);
}
/** Checks the given image for valid width and height. */
private static void checkImage( Image image ) {
waitForImage( image );
int imageWidth = image.getWidth( null );
if ( imageWidth < 1 )
throw new IllegalArgumentException( "image width " + imageWidth + " is out of range" );
int imageHeight = image.getHeight( null );
if ( imageHeight < 1 )
throw new IllegalArgumentException( "image height " + imageHeight + " is out of range" );
}
/** Waits for given image to load. Use before querying image height/width/colors. */
private static void waitForImage( Image image ) {
try {
tracker.addImage( image, 0 );
tracker.waitForID( 0 );
tracker.removeImage(image, 0);
} catch( InterruptedException e ) { e.printStackTrace(); }
}
/** Encodes the given image at the given quality to the output stream. */
private static void encode( OutputStream outputStream, Image outputImage, String format )
throws java.io.IOException {
int outputWidth = outputImage.getWidth( null );
if ( outputWidth < 1 )
throw new IllegalArgumentException( "output image width " + outputWidth + " is out of range" );
int outputHeight = outputImage.getHeight( null );
if ( outputHeight < 1 )
throw new IllegalArgumentException( "output image height " + outputHeight + " is out of range" );
// Get a buffered image from the image.
BufferedImage bi = new BufferedImage( outputWidth, outputHeight,
BufferedImage.TYPE_INT_RGB );
Graphics2D biContext = bi.createGraphics();
biContext.drawImage( outputImage, 0, 0, null );
ImageIO.write(bi, format, outputStream);
outputStream.flush();
}
/**
* 缩放gif图片
* @param originalFile 原图片
* @param resizedFile 缩放后的图片
* @param newWidth 宽度
* @param quality 缩放比例 (等比例)
* @throws IOException
*/
private static void resize(File originalFile, File resizedFile, int newWidth, float quality) throws IOException {
if (quality < 0 || quality > 1) {
throw new IllegalArgumentException("Quality has to be between 0 and 1");
}
ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
Image i = ii.getImage();
Image resizedImage = null;
int iWidth = i.getWidth(null);
int iHeight = i.getHeight(null);
if (iWidth > iHeight) {
resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) / iWidth, Image.SCALE_SMOOTH);
} else {
resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight, newWidth, Image.SCALE_SMOOTH);
}
// This code ensures that all the pixels in the image are loaded.
Image temp = new ImageIcon(resizedImage).getImage();
// Create the buffered image.
BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null),
BufferedImage.TYPE_INT_RGB);
// Copy image to buffered image.
Graphics g = bufferedImage.createGraphics();
// Clear background and paint the image.
g.setColor(Color.white);
g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
g.drawImage(temp, 0, 0, null);
g.dispose();
// Soften.
float softenFactor = 0.05f;
float[] softenArray = {0, softenFactor, 0, softenFactor, 1-(softenFactor*4), softenFactor, 0, softenFactor, 0};
Kernel kernel = new Kernel(3, 3, softenArray);
ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
bufferedImage = cOp.filter(bufferedImage, null);
// Write the jpeg to a file.
FileOutputStream out = new FileOutputStream(resizedFile);
// Encodes image as a JPEG data stream
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);
param.setQuality(quality, true);
encoder.setJPEGEncodeParam(param);
encoder.encode(bufferedImage);
}
}
允许用户上传文件,那么我们一定要注意安全,如果用户上传了一个jsp文件,而这个文件的上传路径敲好能被用户访问到,那么用户可能会在这个jsp文件里面做一个对网站其他文件的文件操作,可以将文件保存到web-inf下面,如果用户需要下载,我们就写一个servlet读取这个文件,以流的方式返回给用户。
分享到:
相关推荐
巴巴运动网商品交易系统详细设计说明书 可作为毕业设计开题报告用
2016年版新巴巴运动网项目12天完整视频教程以及源码,
巴巴运动网商品交易系统是一套面向大型企业开发的商品交易系统,具备先进的电子商务运营及管理理念。订单流转实现多部门协同处理,满足大型企业多部门协作处理业务的需求。系统包含以下模块: 产品管理:产品具有...
巴巴运动网源码和jar文件,完整的源码和用到的jar文件。工程配置后可直接运行。。。
巴巴运动网源码 emmmmm 最低2分了 emmmmmmm 啧啧啧啧啧啧
巴巴运动网 基于分布式构架的大型商品交易平台,系统围绕一个业务中心的思想,实现了多种类型的客户端应用,如:基于浏览器的web交易系统,基于手机的wap交易系统,用于内部办公的OA系统,像这些系统都使用了同一个...
巴巴运动网 部分 前端代码 没用图片 嵌进去即可用了
更重要的是巴巴运动网是真正的商业化产品(售价12万元),它溶合了作者多年积累的商务网站运营及软件构架经验,是目前为数不多的集网站运营、业务处理及技术于一身的商品交易系统。是网上流传的商城系统无法比拟的。
传智巴巴运动网源代码 传智巴巴运动网源代码 传智巴巴运动网源代码 传智巴巴运动网源代码 传智巴巴运动网源代码 传智巴巴运动网源代码
这个是完整版的巴巴运动网的源代码,可以部署运行,希望大家可以下载作参考!
巴巴运动网 源码下载,很好的资源,欢迎大家免费下载学习。
本资源包括传智播客的巴巴运动网源码,Java代码
巴巴运动网项目jar包完整版 巴巴运动网项目jar包完整版
巴巴运动网 jar包,很好的资源,欢迎大家免费下载学习。
图片压缩,阿里巴巴SimpleImage 相关jar文件。其中包含依赖jar: commons-io-2.4.jar;commons-lang.jar;commons-logging-1.1.1.jar jai_codec-1.1.3.jar;jai_core-1.1.3.jar; 包含jar:aliSimpleImage.jar。...
新巴巴项目需求文档 页面源码 运动商品网站 前台后台ii
巴巴运动网完整源代码压缩包,即巴巴运动网106集和后续视频的所有代码!
python + selenium +pyquery 爬虫 爬取 1688详情图片 阿里巴巴详情图片 与标题 下载图片并进行压缩 仅供学习交流使用
传智播客新巴巴运动网项目中用于分页的page包,下载后放入maven本地仓库即可使用