Java如何实现压缩图片大小
导读:本文共1138.5字符,通常情况下阅读需要4分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: 使用场景:1.当使用图片上传功能时,上传图片太大,造成对服务器资源过多的占用2.客户端上传图片尺寸大小不一,前端需要展示给用户固定尺寸时,可通过java进行对上传图片统一进行处理功能预览1.压缩前2.压缩后代码实现:packagecom.linghu.test;importcom.sun.image.codec.jpeg.JPEGCodec;importc... ...
音频解说
使用场景:
1.当使用图片上传功能时,上传图片太大,造成对服务器资源过多的占用
2.客户端上传图片尺寸大小不一,前端需要展示给用户固定尺寸时,可通过java进行对上传图片统一进行处理
功能预览
1.压缩前
2.压缩后
代码实现:
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如何实现压缩图片大小的详细内容,希望对您有所帮助,信息来源于网络。