本文参考传智播客巴巴运动网视频教程
构建保存图片的路径:
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读取这个文件,以流的方式返回给用户。
分享到:
相关推荐
3. **数据库脚本**:SQL文件,用于创建和管理数据库结构,存储用户信息、基金数据、交易记录等。 4. **配置文件**:如`.ini`或`.php`文件,存放系统设置,如数据库连接信息,应用环境变量等。 5. **类库和框架**:...
这个定制版可能包括了针对大规模分布式系统的特性,如负载均衡、故障恢复、性能监控以及安全性强化等。 【标签】"taobao-tomca" 可能是标签输入错误,正确的应该是 "taobao-tomcat",表示这个版本与淘宝公司和...
Kotti 是一个基于 Pyramid 框架的 Python 内容管理系统(CMS),适合用来搭建中小型网站、文档库、企业展示平台、知识库等需要灵活内容结构和权限模型的项目。它本身更像一个可以二次开发的 CMS 框架,比 WordPress、Drupal 这类“一装就用”的系统更倾向于开发者定制和扩展。 这是支持pyramid2.x版本的kotti! tar -xzvf kotti1.0.tar.gz 解压缩 进入目录执行 pip install -e . 来安装, 然后执行pserve app.ini 启动。 用浏览器浏览127.0.0.1:5000 即可浏览。 用户名admin ,口令qwerty
cmd-bat-批处理-脚本-hello world.zip
知识付费系统自动采集V3.0 跳转不卡顿+搭建教程,不和外面的一样跳转卡顿,这个跳转不卡顿,支持三级分销。
在Matlab环境下,对图像进行特征提取时,主要涵盖形状、纹理以及颜色这三大关键特征。其中,对于纹理特征的提取,采用灰度梯度共生矩阵这一方法来实现。通过灰度梯度共生矩阵,可以有效地捕捉图像中像素灰度值之间在不同方向和距离上的相互关系,进而量化地反映出图像的纹理特性,为后续的图像分析、分类等任务提供重要的纹理信息依据。
该数据集为2010-2023年中国A股上市公司管理层情感语调的年度面板数据,覆盖45,320条样本,数据源自年报及半年报的"管理层讨论与分析"部分。通过构建中文金融情感词典(融合《知网情感分析用词典》与L&M金融词汇表),采用文本分析方法计算情感语调指标,包括:正面/负面词汇数量、文本相似度、情感语调1((积极词-消极词)/总词数)和情感语调2((积极词-消极词)/(积极词+消极词))。同时包含盈利预测偏差、审计意见类型等衍生指标,可用于研究信息披露质量、市场反应及代理问题。该数据复刻了《管理世界》《财经研究》等期刊的变量构建方法,被应用于分析语调操纵对债券市场的影响,学术常用度与稀缺度较高。
cmd-bat-批处理-脚本-FTIME.zip
1747829038637.png
2025年自动化X光检查机项目大数据研究报告.docx
在计算机组成原理课程设计中,我全程跟随老师的指导,独立完成了以下两项任务:一是利用Logisim软件进行原码一位乘法器的仿真设计,通过逐步搭建电路、配置逻辑单元,实现了原码乘法运算的完整流程,深入理解了原码乘法的原理和实现机制;二是完成了补码一位乘法器的Logisim仿真,同样按照老师讲解的步骤,精心设计电路,确保补码乘法运算的正确性,进一步掌握了补码乘法的运算规则和电路实现方法。通过这两个项目,我不仅巩固了理论知识,还提升了动手实践能力和逻辑思维能力。
cmd-bat-批处理-脚本-msvc2017.zip
cmd-bat-批处理-脚本-virtualcam-install.zip
二十四节气之立秋介绍.pptx
cmd-bat-批处理-脚本-shift.zip
二十四节气之小雪介绍.pptx
java、SpringBoot面试专题,6页面试题
cmd-bat-批处理-脚本-GenerateUnionWinMD.zip
二十四节气之大暑节气.pptx
python实现五子棋游戏源码