-
图片大小压缩0
package com.baosight.ec.userCenter.seller.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.upload.FormFile;
import com.baosight.ec.common.Constants;
import com.baosight.ec.common.EcBaseAction;
import com.baosight.web.struts.BActionContext;
import com.bsteel.exchange.client.common.util.PropertiesUtil;
/**
* 图片管理
*
* @author
* @date 2013-11-1 下午2:23:52
*/
public class ImgManageAction extends EcBaseAction {
@Override
public ActionForward doDefault(BActionContext context) throws Exception {
// TODO Auto-generated method stub
return null;
}
/*
* 图片上传
*/
@SuppressWarnings("unchecked")
public void uploadImg(BActionContext context) throws IOException{
ActionForm beanForm = context.getForm();
String msg = "";
String path = "";
StringBuilder json = new StringBuilder();
Hashtable<String, FormFile> fileh = beanForm.getMultipartRequestHandler().getFileElements();
List<FormFile> fileList= new ArrayList<FormFile>();
for (Iterator<String> it = fileh.keySet().iterator(); it.hasNext();) {
String key = it.next();
FormFile formfile = fileh.get(key);
if(formfile.getFileSize()>0){
fileList.add(formfile);
}
}
if(fileList.size()>0){
FormFile file = fileList.get(0);
if(file!=null){
int i = file.getFileSize();
if(file.getFileSize()<=500*1024){
try {
path = upload(fileList.get(0));
msg = "上传成功";
} catch (Exception e) {
msg = "错误:"+e.getMessage();
}
}else{
msg = "tooLarge";
}
}
}
json.append("{path:'"+path+"',msg:'"+msg+"'}");
context.getResponse().setContentType("text/html;charset=UTF-8");
PrintWriter printWriter = context.getResponse().getWriter();
printWriter.write(json.toString());
printWriter.flush();
printWriter.close();
}
private String upload(FormFile file) throws IOException{
String serverFileName ="";
if(file!=null){
//ResourceBundle rb = ResourceBundle.getBundle(Constants.SYSTEM.PROPERTIES_FILE);
String filePath = Constants.IMAGE_UPLOAD_PATH;
//本机测试用的路径,不上传
//filePath="D:\\upload\\";
System.out.println("========filePath======="+filePath);
//String runFlag = rb.getString("run.flag");//标识是在哪台服务器上运行(a:103,b:68)
//System.out.println("此服务器的运行标识是:=========》"+runFlag+"<==========");
//判断要上传的文件目录是否存在,如果不存在则创建目录
File tempfile = new File(filePath);
if(!tempfile.exists()){
tempfile.mkdir();
}
//图片上传服务器
String path = null;
String localFileName =file.getFileName();
serverFileName = System.currentTimeMillis()+localFileName.substring(localFileName.lastIndexOf("."));
path = filePath+serverFileName;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(path);
fos.write(file.getFileData());
fos.flush();
fos.close();
System.out.println("FTP服务器传送文件开始!!!");
boolean transFlag=this.transFile(path,serverFileName);
if(transFlag){//传送成功后,删除原路径的文件
boolean deleFlag=new File(path).delete();
if(deleFlag){
System.out.println("文件:====>"+path+"<====删除成功!");
}
}else {//上传文件失败
System.out.println("文件:====>"+path+"<====上传失败!");
}
} catch (Exception e) {
e.printStackTrace();
} finally{//关闭资源
if(fos!=null){
fos.close();
}
}
}
return serverFileName;
}
/**
* 将本地服务器的文件传输到目标服务器指定目录
* @param path 本地服务器的文件名(完整路径)
* @param serverFileName 根据系统时间重命名的文件名
* @throws SocketException
* @throws IOException
*/
private boolean transFile(String path, String serverFileName) throws SocketException, IOException {
//判断文件是否传送成功的标识
boolean result=false;
String ftpAddress = Constants.FTP_ADDRESS;
String ftpUser = Constants.FTP_USER;
String ftpPassword = Constants.FTP_PASSWORD;
String imageTargetDir = Constants.FTP_TARGETDIR;
//测试用的URL和路径
//ftpAddress="10.60.17.145";
//imageTargetDir="/export/home/jboss/jboss/jboss-3.2/server/default/deploy/webdocs.war/baozypj/upload_image/";
System.out.println("========ftpAddress======="+ftpAddress);
System.out.println("========ftpUser======="+ftpUser);
System.out.println("========ftpPassword======="+ftpPassword);
System.out.println("========imageTargetDir======="+imageTargetDir);
FTPClient ftp=new FTPClient();
ftp.connect(ftpAddress);//连接服务器
ftp.login(ftpUser, ftpPassword);//登录
//判断连接是否成功
int reply=ftp.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)){
System.out.println("连接失败");
ftp.disconnect();
return false;
}
//String workPath = filePath;//工作目录名
String workPath = imageTargetDir;
String remoteFileName=imageTargetDir+serverFileName;//远程文件名
Boolean b=ftp.changeWorkingDirectory(workPath);//设置工作目录
System.out.println("目标服务器文件名(全路径):=======>"+remoteFileName+"<==========");
//FileInputStream fis2=new FileInputStream(path);
File remoteFile=new File(path);//以本地服务器的文件作为输入流
//System.out.println("文件的大小为:"+remoteFile.length());
FileInputStream fis2=new FileInputStream(remoteFile);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
if(b){
Boolean b2=ftp.storeFile(new String(remoteFileName.getBytes(),"iso-8859-1"), fis2);
if(b2){
System.out.println("上传成功!图片的大小为:"+remoteFile.length()+"字节");
if(remoteFile.length()>0){
result=true;
}
}
fis2.close();
ftp.logout();
}
return result;
}
/*
* 本地图片删除
*/
public void deletePic(BActionContext context) throws IOException {
// ResourceService resourceService = (ResourceService)context.findService("resourceService", ResourceService.class);
String filePath = Constants.IMAGE_UPLOAD_PATH;
String imgName = context.getRequest().getParameter("imgName");
String msg = "";
boolean r = false;
File file = new File(filePath+imgName);
if(file.exists()){
r = file.delete();
if(r){
// resourceService.deleteResourceImgByImgName(imgName);
msg = "0";
}else{
msg = "删除错误";
}
}
context.getResponse().setContentType("text/html;charset=UTF-8");
PrintWriter printWriter = context.getResponse().getWriter();
printWriter.write(msg);
}
}
这是我这里的图片上传代码
我想在上传代码哪里的判断图片大于500KB的方法里加入一个图片压缩方法,当图片大于500KB进入此方法进行压缩为更小的KB,然后返回处理过的图片在进入上传图片方法上传!请问代码怎么写2014年10月13日 16:06
1个答案 按时间排序 按投票排序
-
采纳的答案
package com.kay.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.awt.image.BufferedImage;
import java.awt.Image;
import java.awt.image.AffineTransformOp;
import javax.imageio.ImageIO;
import java.awt.geom.AffineTransform;
public class ImageModify {
/**
* @param filePath
* 图片的原始目录
* @param dirPath
* 处理后的图片存放目录
* @param file
* 原始图片
* @param dirName
* 处理后的图片文件名前缀
* @throws Exception
*
*/
public static void main(String []args) throws Exception{
// ImageModify m=new ImageModify();
// String filePath="f://image";
// String dirPath="f://image";
// String file="a.gif";
// String dirName="img"+(new Date()).getTime();
// if(m.modify(filePath,dirPath,file,dirName)){
// System.out.println("图像处理成功!");
// }
}
public static void modify(String filePath,String dirPath,String file,String dirName) throws Exception {
// ext是图片的格式 gif JPG 或png
String ext = "";
double Ratio = 0.0;
File F = new File(filePath, file);
// if (!F.isFile())
// throw new Exception(F
// + " is not image file error in CreateThumbnail!");
// 首先判断上传的图片是gif还是JPG ImageIO只能将gif转换为png
// if (isJpg(imgfile)) {
// ext = "jpg";
// } else {
ext = "jpg";
// }
File dir=new File(dirPath);
if(!dir.exists()){
dir.mkdir();
}
File ThF = new File(dirPath, dirName);
if(!ThF.exists()){
ThF.createNewFile();
}
BufferedImage Bi = ImageIO.read(F);
// 假设图片宽 高 最大为120 120
Image Itemp = Bi.getScaledInstance(120, 120, Bi.SCALE_SMOOTH);
if ((Bi.getHeight() > 120) || (Bi.getWidth() > 120)) {
if (Bi.getHeight() > Bi.getWidth())
Ratio = 120.0 / Bi.getHeight();
else
Ratio = 120.0 / Bi.getWidth();
}
AffineTransformOp op = new AffineTransformOp(AffineTransform
.getScaleInstance(Ratio, Ratio), null);
Itemp = op.filter(Bi, null);
try {
ImageIO.write((BufferedImage) Itemp, ext, ThF);
} catch (Exception ex) {
throw new Exception(" ImageIo.write error in CreatThum.: "
+ ex.getMessage());
}
// return (true);
}
public static void upload(File file, String fileName, String path) throws IOException{
InputStream is = null;
OutputStream os = null;
try
{
File dir = new File(path);
if (!dir.exists())
{
dir.mkdirs();
}
if (!file.exists())
{
file.createNewFile();
}
is = new FileInputStream(file.toString());
String name = fileName.trim().toString();// 得到上传文件的原名称
File destFile = new File(path, name);
os = new FileOutputStream(destFile);
byte[] buffer = new byte[400];
int length = 0;
while ((length = is.read(buffer)) > 0)
{
os.write(buffer, 0, length);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
is.close();
os.close();
}
}
}
不晓得这个是不是你要的效果2014年10月13日 16:54
相关推荐
为了应对这一挑战,应运而生了“图片大小压缩工具”。这款工具提供了一个有效的解决方案,帮助用户在不牺牲太多图像质量的前提下,大幅减小图片文件的体积。通过精确掌握压缩比例,用户可以自由调整图片大小,使得...
标题 "图片大小压缩,拖拽图片覆盖原图" 指涉的是一个图像处理软件或服务,它允许用户轻松地减小图片文件的大小。在数字化时代,图片大小的优化对于存储、分享和加载速度至关重要,尤其是在网页设计、社交媒体发布和...
这款名为“极好用图片大小压缩及水印软件”的工具,正是针对这一需求而设计的高效解决方案。下面我们将深入探讨这款软件的主要功能、应用价值以及可能涉及的技术知识点。 首先,批量修改大小是这款软件的核心功能之...
通过java实现对图片按照尺寸、像素质量实现对图片的压缩处理,并可以对图片制定宽高或者等比压缩
它可以快速调整图片大小、改变格式并进行批量压缩,适合个人和企业用户。 - Adobe Photoshop:虽然功能强大,但操作相对复杂,支持批处理功能。 - GIMP:免费开源的图像编辑软件,同样具备批处理能力。 - ...
RIOT 全称 Radical Image Optimization Tool,意为 激进的图像优化工具,可以直观地调整压缩参数,同时保持最小文件大小。 RIOT 使用双窗口实时比较原图与优化的图像,由于全部在内存中完成,速度很快,通过控制...
根据提供的文件信息,我们可以深入探讨...综上所述,C#中的图片无损压缩不仅可以有效地减小文件大小,而且还能保持原始图像的质量不变。通过合理设置压缩参数和采用适当的算法,可以在不同场景下获得最佳的压缩效果。
图片大小压缩器可以轻松帮助你压缩图片的一款轻巧好用的 图片压缩器软件,压缩率越高,图片占用空间就越小, 但图片质量越差,大家要清楚这点。 【使用方法】 1、首先打开图片,也可直接把图片拖进压缩工具窗口 2...
比较好用的图片压缩工具,可以大幅度压缩图片的大小,图片质量损失较小。本人已使用过,可用,无毒。
图片等比例压缩,同时图片大小压缩。经本人测试,800k的图片压缩过后只有几十k,图片效果差不多。
本主题将深入探讨如何使用Java实现图片压缩,并能够将其调整到任意大小,同时保持图片质量并避免变形。 首先,我们需要理解图片压缩的基本原理。图片压缩主要有两种类型:有损压缩和无损压缩。有损压缩会牺牲一部分...
总的来说,C++图像压缩算法利用霍夫曼编码可以在保留图像质量的同时有效减少文件大小。这种技术广泛应用于数字图像存储、网络传输和多媒体应用中。通过深入理解图像数据的结构和压缩原理,开发者可以设计出更高效、...
本文将详细讲解图片压缩的基本原理、常见方法以及如何使用“图片压缩.exe”这样的工具来优化图片大小。 首先,我们需要理解图片压缩的基本概念。图片压缩分为无损压缩和有损压缩两种类型。无损压缩能够在压缩后恢复...
这个主题主要涉及如何利用Java来减少图片文件的大小,包括静态图片(如JPEG、PNG)以及动态图片(如GIF)。下面我们将深入探讨相关的知识点。 首先,Java中的核心库`javax.imageio`提供了对图片读取、写入和处理的...
描述中提到的“微软出的图片看图和图片大小压缩工具”,可能是微软的Picture Manager 2010,这是一个集成在Microsoft Office套件中的应用程序,用于查看、编辑和管理图片。它提供了方便的图片压缩功能,用户可以通过...
本文将详细介绍如何使用C# .Net技术来实现图片压缩,使得压缩后的图片大小仅为原图的1/10。 #### 压缩原理与方法 在讨论具体的代码实现之前,我们首先需要了解图片压缩的基本原理。图片压缩主要分为两种类型:无损...
标题中的“用来压缩图片大小的工具”指的是一个用于减小图像文件体积的软件或应用程序,主要针对的是JPEG(jpg)格式的图片。在数字图像处理领域,图片的大小往往受到像素数量、颜色深度以及压缩算法的影响。这类...
图片尺寸及大小压缩工具,不需要PS就可以改变图片尺寸及大小