700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > java将模糊的图片变清晰_java高清图生成缩略图变得模糊

java将模糊的图片变清晰_java高清图生成缩略图变得模糊

时间:2023-11-07 14:51:00

相关推荐

java将模糊的图片变清晰_java高清图生成缩略图变得模糊

上传一张高清图,生成两张不同大小的缩略图,缩略图变的很模糊。png的图片变成黑色背景了。代码如下

public void changImg(String path){

try{

Filej_file=new java.io.File(getHTTP.getServletContext().getRealPath("")+"/upfiles/newsImg/goods");

if(!j_file.exists()){

j_file.mkdirs();

}

//----上传完成,开始生成缩略图---goods

java.io.File goods_file = new java.io.File(getHTTP.getServletContext().getRealPath("")+"/"+path);//读入刚才上传的文件

String newpath=path.substring(0, path.lastIndexOf("/"));

String fileName=path.substring(path.lastIndexOf("/")+1, path.length());

String newgoods_url=getHTTP.getServletContext().getRealPath("")+"/"+newpath+"/goods/"+fileName;//新的缩略图保存地址

Image src=javax.imageio.ImageIO.read(goods_file);

float tagsize=400;

int old_w=src.getWidth(null);//得到源图宽

int old_h=src.getHeight(null);

int new_w=0;

int new_h=0;//得到源图长

int tempsize;

float tempdouble;

if(old_w>old_h){

tempdouble=old_w/tagsize;

}else{

tempdouble=old_h/tagsize;

}

new_w=Math.round(old_w/tempdouble);

new_h=Math.round(old_h/tempdouble);//计算新图长宽

BufferedImage tag = new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);

tag.getGraphics().drawImage(src,0,0,new_w,new_h,null);//绘制缩小后的图

FileOutputStream newimage=new FileOutputStream(newgoods_url); //输出到文件流

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);

encoder.encode(tag); //近JPEG编码

newimage.close();

//----上传完成,开始生成缩略图---thumb

java.io.File thumb_file = new java.io.File(getHTTP.getServletContext().getRealPath("")+"/"+path);//读入刚才上传的文件

String newthumb_url=getHTTP.getServletContext().getRealPath("")+"/"+newpath+"/thumb/"+fileName;//新的缩略图保存地址

j_file=new java.io.File(getHTTP.getServletContext().getRealPath("")+"/upfiles/newsImg/thumb");

if(!j_file.exists()){

j_file.mkdirs();

}

Image thumb_src = javax.imageio.ImageIO.read(thumb_file);//构造Image对象

float thumb_tagsize=80;

int thumb_old_w=thumb_src.getWidth(null);//得到源图宽

int thumb_old_h=thumb_src.getHeight(null);

int thumb_new_w=0;

int thumb_new_h=0;//得到源图长

int thumb_tempsize;

float thumb_tempdouble;

if(thumb_old_w>thumb_old_h){

thumb_tempdouble=thumb_old_w/thumb_tagsize;

}else{

thumb_tempdouble=thumb_old_h/thumb_tagsize;

}

thumb_new_w=Math.round((thumb_old_w/thumb_tempdouble));

thumb_new_h=Math.round(thumb_old_h/thumb_tempdouble);//计算新图长宽

BufferedImage thumb_tag = new BufferedImage(thumb_new_w,thumb_new_h,BufferedImage.TYPE_INT_RGB);

thumb_tag.getGraphics().drawImage(thumb_src,0,0,thumb_new_w,thumb_new_h,null);//绘制缩小后的图

FileOutputStream thumb_newimage=new FileOutputStream(newthumb_url); //输出到文件流

JPEGImageEncoder thumb_encoder = JPEGCodec.createJPEGEncoder(thumb_newimage);

thumb_encoder.encode(thumb_tag); //近JPEG编码

thumb_newimage.close();

}catch(Exception e){

e.printStackTrace();

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。