public String LoadImageToServer(String filePath,String serverPath) throws Exception {
String resultPath = ""; //上传后图片所在的路径
FileOutputStream out = null; //文件输出流
try { //验证图片上传的格式是否正确
File f = new File(filePath);
if (!f.isFile()) {
throw new Exception(f " 不是图片文件!");
}
if (f != null && f.exists()) { //这里的ImageIO属于java工厂类,在工厂类class里面,调用的System.gc(),频繁调用会造成dump,需要考虑优化
BufferedImage image = ImageIO.read(f); // 读入文件
if (image != null) {
BufferedImage tag = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); //构造一个类型为预定义图像类型之一的 BufferedImage
tag.getGraphics().drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null); //绘制所需要尺寸大小的图片
/*
* 以下生成图片上传后在服务器上的新路径
*/
int lastLength = filePath.lastIndexOf(".");
Date date = new Date(System.currentTimeMillis());
String strDate = new SimpleDateFormat("yyyyMMddhhmmss").format(date);
int random = (int)(Math.random()*99);
String imageName = strDate random; //以系统时间来随机的创建图片文件名
String fileType = filePath.substring(lastLength); //获取上传图片的类型
resultPath = serverPath "site" imageName fileType;
/*
* 进行图片的绘制
*/
out = new FileOutputStream(resultPath);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param =
encoder.getDefaultJPEGEncodeParam(tag);
param.setQuality(0.95f, true); //95%图像
param.setDensityUnit(1); //像素尺寸单位.像素/英寸
param.setXDensity(300); //水平分辨率
param.setYDensity(300); //垂直分辨率
encoder.setJPEGEncodeParam(param);
encoder.encode(tag);
tag = null;
}
}
f = null;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
out.close();
out = null;
}
return resultPath;
}
分享到:
相关推荐
java上传文件到服务器,将本地的文件上传到服务器上去
java实现上传文件到远程服务器(spring mvc)
JAVA中生成xml文件到指定路径和上传到ftp服务器到指定路径的方法。
从本地上传图片到服务器,!!!分享给大家!!!
esp8266上传温湿度数据到本地java服务器并将数据存到数据库,可以将java程序部署到服务器上,只需要把jdbc里面的配置和wifi模块的配置改一下即可
使用Java远程上传压缩包到服务器,或者在服务器上拉去压缩包或者文件,在服务器上创建目录。
js调用本地摄像头拍照并上传到web服务器。后台使用java实现图片的接收和存储,上传的图片默认保存到项目下的images文件夹中。
拍照、选择本地图片、文字、上传到服务器.代码
在各大网站上都可以实现上传头像功能,可以选择自己喜欢的图片做头像,从本地上传,今天小编给大家分享Java实现图片上传到服务器并把上传的图片读取出来,需要的朋友参考下
java 文件上传服务器,前后台代码
1.JAVA 监听文件夹变化 2.模拟POST提交文件流同步服务器文件
主要为大家详细介绍了Java上传文件图片到服务器的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下