Java如何实现压缩图片大小(java,开发技术)

时间:2024-04-28 06:25:28 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

使用场景:

1.当使用图片上传功能时,上传图片太大,造成对服务器资源过多的占用
2.客户端上传图片尺寸大小不一,前端需要展示给用户固定尺寸时,可通过java进行对上传图片统一进行处理

功能预览

1.压缩前

Java如何实现压缩图片大小

2.压缩后

Java如何实现压缩图片大小

代码实现:

packagecom.linghu.test;importcom.sun.image.codec.jpeg.JPEGCodec;importcom.sun.image.codec.jpeg.JPEGImageEncoder;importjavax.imageio.ImageIO;importjava.awt.image.BufferedImage;importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;/**@author在下令狐*@describe压缩图片大小*@date2020/6/12*/publicclassTestCompressImage{publicstaticvoidmain(String[]args){try{//图片所在路径BufferedImagetemplateImage=ImageIO.read(newFile("f:/temp/linghu.jpg"));//原始图片的长度和宽度intheight=templateImage.getHeight();intwidth=templateImage.getWidth();//通过比例压缩floatscale=0.5f;//通过固定长度压缩/*intdoWithHeight=100;intdowithWidth=300;*///压缩之后的长度和宽度intdoWithHeight=(int)(scale*height);intdowithWidth=(int)(scale*width);BufferedImagefinalImage=newBufferedImage(dowithWidth,doWithHeight,BufferedImage.TYPE_INT_RGB);finalImage.getGraphics().drawImage(templateImage.getScaledInstance(dowithWidth,doWithHeight,java.awt.Image.SCALE_SMOOTH),0,0,null);//图片输出路径,以及图片名FileOutputStreamfileOutputStream=newFileOutputStream("f:/temp/linghuAfterDoWith.jpg");JPEGImageEncoderencoder=JPEGCodec.createJPEGEncoder(fileOutputStream);encoder.encode(finalImage);fileOutputStream.close();}catch(IOExceptione){e.printStackTrace();}}}
 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:Java如何实现压缩图片大小的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:vue v-model怎么使用下一篇:

10 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18