日期:2014-05-18  浏览次数:20641 次

上传图片生成缩略图的问题,急
在项目中要用到上传图片并生成缩略图的问题,我不知该如何做,主要问题是生成比较清晰的缩略图的代码,
请大家帮忙,还是就是怎样限定图片的上传时的尺寸,比如说只允许800*600,该怎么判断

------解决方案--------------------
比较简单:
public static double LIMITEDWIDTH_R018=320;
public static double LIMITEDHEIGHT_R018=320;


/**
* 图象等比缩小
* @param wid - int 原图象的width,高
* @param hei - int 原图象的宽度
* */
public static int[] changewh(double wid,double hei,
double limit_width,double limit_height)
{
double width;
double height;
double multiple;
double multiple1;
double multiple2;
double ww_limited=limit_width;//限定的高度
double hh_limited=limit_height;//限定的宽度
multiple=ww_limited/hh_limited;//指定比例的比例大小
multiple1=wid/hei;//图片的原比例大小
multiple2=wid/ww_limited;
//等比缩小
if((wid> ww_limited)|(hei> hh_limited))
{
double rate1=wid/ww_limited;
double rate2=hei/hh_limited;
if(rate1> rate2)
{
width=ww_limited;
height=hei/rate1;
}
else
{
height=limit_height;
width=wid/rate2;
}
}else{
width=wid;
height=hei;
}
width=Integer.parseInt(round(width,0));
height=Integer.parseInt(round(height,0));
int[] temp=new int[2];
temp[0]=(int)width;
temp[1]=(int)height;
return temp;
}


private BufferedImage getImage(String imagePath,
double limit_width,double limit_height){

// Create the buffered image.

Image image = null;
try{
image=javax.imageio.ImageIO.read(new File(imagePath));
}catch(Exception e){
//return null;
}

int width=image.getWidth(null);
int height=image.getHeight(null);
int[] changedSize=changewh((double)width,(double)height,
limit_width,limit_height);
int changeWidth=changedSize[0];
int changeHeight=changedSize[1];

BufferedImage bufferedImage = new BufferedImage(
changeWidth, changeHeight,
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, changeWidth, changeHeight);
g.drawImage(image, 0, 0,changeWidth, changeHeight, null);
g.dispose();
return bufferedImage;

}


调用就调用getImage方法返回一个imagebuffer,稍微改造一下就可以生成一个800*600的图片了