java应用程序中写的一个图片压缩的demo在web应用程序中压缩的图片大小为0,应用程序中是正常的

public void saveImageAsFormat(File fromFile,int targetW,String imgType,String toSaveFile) throws IOException{

    BufferedImage srcImage = null,tgtImage=null;

    srcImage = ImageIO.read(fromFile);
    int type = srcImage.getType();
    int targetH=0;
    double sx = (double) targetW / srcImage.getWidth();
    targetH = (int) (sx * srcImage.getHeight());//获得压缩图片的高度

    if (type == BufferedImage.TYPE_CUSTOM) {
         ColorModel cm = srcImage.getColorModel();
         WritableRaster raster = cm.createCompatibleWritableRaster(targetW,targetH);
         boolean alphaPremultiplied = cm.isAlphaPremultiplied();
         tgtImage = new BufferedImage(cm, raster, alphaPremultiplied, null);
    } else {
        tgtImage = new BufferedImage(targetW, targetH, type);
    }
    Graphics2D g = tgtImage.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_RENDERING,
    RenderingHints.VALUE_RENDER_QUALITY);
    g.drawRenderedImage(srcImage, AffineTransform.getScaleInstance(sx, sx));
    g.dispose();

    File saveFile = new File(toSaveFile);

    ImageIO.write(tgtImage, imgType, saveFile);

}

[quote]图片保存到目标路径了,但大小是0,测试了下压缩时间,也是花时间了的,所以和纠结。[/quote]
那你看看在web程序和普通应用程序执行的时候差别在哪里?

[code="java"]我给你个例子

用Java实现zip压缩文件和目录程序代码

今天写了个用java压缩的功能,可以实现对文件和目录的压缩。

由于java.util.zip.ZipOutputStream有中文乱码问题,所以采用org.apache.tools.zip.ZipOutputStream。
以下是代码:
Java代码
package net.szh.zip;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

public class ZipCompressor {
static final int BUFFER = 8192;

private File zipFile;

public ZipCompressor(String pathName) {
zipFile = new File(pathName);
}

public void compress(String srcPathName) {
File file = new File(srcPathName);
if (!file.exists())
throw new RuntimeException(srcPathName + "不存在!");
try {
FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,
new CRC32());
ZipOutputStream out = new ZipOutputStream(cos);
String basedir = "";
compress(file, out, basedir);
out.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}

private void compress(File file, ZipOutputStream out, String basedir) {
/* 判断是目录还是文件 */
if (file.isDirectory()) {
System.out.println("压缩:" + basedir + file.getName());
this.compressDirectory(file, out, basedir);
} else {
System.out.println("压缩:" + basedir + file.getName());
this.compressFile(file, out, basedir);
}
}

/** 压缩一个目录 */
private void compressDirectory(File dir, ZipOutputStream out, String basedir) {
if (!dir.exists())
return;

File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
/* 递归 */
compress(files[i], out, basedir + dir.getName() + "/");
}
}

/** 压缩一个文件 */
private void compressFile(File file, ZipOutputStream out, String basedir) {
if (!file.exists()) {
return;
}
try {
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(file));
ZipEntry entry = new ZipEntry(basedir + file.getName());
out.putNextEntry(entry);
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
bis.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

本篇文章来自Java中文网:http://www.javaweb.cc/language/java/222365.shtml

[/code]

[code="java"][/code]

看看是否是路径问题或者是

[code="java"]图片不失真的等比例压缩算法:
算法思想:根据压缩基数和压缩比来压缩原图,生产一张图片效果最接近原图的缩略图。
算法讲解:
public void saveMinPhoto(String srcURL,String deskURL,double comBase,double scale){
/*srcURl 原图地址;deskURL 缩略图地址;comBase 压缩基数;scale 压缩限制(宽/高)比例*/
java.io.File srcFile = new java.io.File(srcURL);
Image src = new javax.imageio.ImageIO.read(srcFile);
int srcHeight = src.getHeight(null);
int srcWidth = src.getWidth(null);
int deskHeight = 0;//缩略图高
int deskWidth = 0;//缩略图宽
double srcScale = (double)srcHeight/srcWidth;
if((double)srcHeight>comBase || (double)srcWidth>comBase){
if(srcScale>=scale || 1/srcScale>scale){
if(srcScale>=scale){
deskHeight = (int)comBase;
deskWidth = srcWidth*deskHeight/srcHeight;
}else{
deskWidth = (int)comBase ;
deskHeight = srcHeight*deskWidth/srcWidth;
}

   } else {
     if((double)srcHeight>comBase){
        deskHeight = (int)comBase;
        deskWidth  = srcWidth*deskHeight/srcHeight;
         } else{
             deskWidth = (int)comBase ;
             deskHeight  = srcHeight*deskWidth/srcWidth;
          }

      } 
  }else {
      deskHeight = srcHeight;
      deskWidth  = srcWidth;

}
BufferedImage tag = new BufferedImage(deskWidth, deskHeight,
BufferedImage.TYPE_3BYTE_BGR);
tag.getGraphics().drawImage(src, 0, 0, deskWidth, deskHeighth, null); //绘制缩小后的图
FileOutputStream deskImage = new FileOutputStream(deskURL); //输出到文件流
JPEGImageEncoder encoder = JPEGCodec
.createJPEGEncoder(deskImage);
encoder.encode(tag); //近JPEG编码
deskImage.close();

}


public class ImgProce {
private int wideth;
private int height;
private String t=null;
public void setT(String t)
{
this.t=t;
}
public void setWideth(int wideth)
{
this.wideth=wideth;
}
public int getWideth()
{
return this.wideth;
}
public void setHeight(int height)
{
this.height=height;
}
public int getHeight()

{
if(w > wideth)
{
float ww;
ww = (float) w / (float) wideth;
float hh = h / ww;
return (int) hh;
}
else
{
this.setWideth(w);
return h;
}
}
public void proce(String fpath) throws Exception
{
File _file = new File(fpath);
Image src = javax.imageio.ImageIO.read(_file);
int wideth=src.getWidth(null);
int height=src.getHeight(null);
int h=this.getHeight(wideth,height);
BufferedImage tag = new BufferedImage(this.getWideth(),h,BufferedImage.TYPE_INT_RGB);
Graphics g=tag.getGraphics();
g.drawImage(src, 0, 0, this.getWideth(), h, null);
if(t!=null)
{
g.setColor(new Color(242,242,242));
g.fillRect(this.getWideth() - 120, h - 18,120,18);
g.setColor(new Color(180,180,180));
g.drawRect(this.getWideth() - 120, h - 18,119,17);
g.setColor(new Color(255,102,0));
g.drawString(t, this.getWideth() - 100, h - 5);
}

 ImageIO.write(tag, "jpg", new File(fpath)); 

}
}


import java.awt.Image;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;

import com.sun.image.codec.jpeg.JPEGEncodeParam;

import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImageZipUtil {

/**  
 * 压缩图片文件<br>  
 * 先保存原文件,再压缩、上传  
 *   
 * @param oldFile  
 *            要进行压缩的文件全路径  
 * @param width  
 *            宽度  
 * @param height  
 *            高度  
 * @param quality  
 *            质量  
 * @param smallIcon  
 *            小图片的后缀  
 * @return 返回压缩后的文件的全路径  
 */  
public static String zipImageFile(String oldFile, int width, int height,   
        float quality, String smallIcon) {   
    if (oldFile == null) {   
        return null;   
    }   
    String newImage = null;   
    try {   
        /** 对服务器上的临时文件进行处理 */  
        Image srcFile = ImageIO.read(new File(oldFile));
        int w = srcFile.getWidth(null);
        System.out.println(w);
        int h = srcFile.getHeight(null);
        System.out.println(h);
        //width = w/4;
        //height = h/4;

        /** 宽,高设定 */  
        BufferedImage tag = new BufferedImage(width, height,   
                BufferedImage.TYPE_INT_RGB);   
        tag.getGraphics().drawImage(srcFile, 0, 0, width, height, null);   
        String filePrex = oldFile.substring(0, oldFile.indexOf('.'));   
        /** 压缩后的文件名 */  
        newImage = filePrex + smallIcon   
                + oldFile.substring(filePrex.length());   

        /** 压缩之后临时存放位置 */  
        FileOutputStream out = new FileOutputStream(newImage);   

        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);   
        JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);   
        /** 压缩质量 */  
        jep.setQuality(quality, true);   
        encoder.encode(tag, jep);   
        out.close();   

    } catch (FileNotFoundException e) {   
        e.printStackTrace();   
    } catch (IOException e) {   
        e.printStackTrace();   
    }   
    return newImage;   
}   

/**  
 * 保存文件到服务器临时路径  
 *   
 * @param fileName  
 * @param is  
 * @return 文件全路径  
 */  
public static String writeFile(String fileName, InputStream is) {   
    if (fileName == null || fileName.trim().length() == 0) {   
        return null;   
    }   
    try {   
        /** 首先保存到临时文件 */  
        FileOutputStream fos = new FileOutputStream(fileName);   
        byte[] readBytes = new byte[512];// 缓冲大小   
        int readed = 0;   
        while ((readed = is.read(readBytes)) > 0) {   
            fos.write(readBytes, 0, readed);   
        }   
        fos.close();   
        is.close();   
    } catch (FileNotFoundException e) {   
        e.printStackTrace();   
    } catch (IOException e) {   
        e.printStackTrace();   
    }   
    return fileName;   
}   
public static void main(String args[]){   
    ImageZipUtil.zipImageFile("E:/009.jpg", 128, 128, 1f, "x2");   

}   

}[/code]

web应用中也是调用同样的方法?
检查一下有没有异常抛出