您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息

Java如何实现压缩图片大小

2024/5/10 7:31:27发布6次查看
使用场景:1.当使用图片上传功能时,上传图片太大,造成对服务器资源过多的占用
2.客户端上传图片尺寸大小不一,前端需要展示给用户固定尺寸时,可通过java进行对上传图片统一进行处理
功能预览1.压缩前
2.压缩后
代码实现:package com.linghu.test;import com.sun.image.codec.jpeg.jpegcodec;import com.sun.image.codec.jpeg.jpegimageencoder;import javax.imageio.imageio;import java.awt.image.bufferedimage;import java.io.file;import java.io.fileoutputstream;import java.io.ioexception;/* * @author 在下令狐 * @describe 压缩图片大小 * @date 2020/6/12 */public class testcompressimage { public static void main(string[] args) { try { //图片所在路径 bufferedimage templateimage = imageio.read(new file("f:/temp/linghu.jpg")); //原始图片的长度和宽度 int height = templateimage.getheight(); int width = templateimage.getwidth(); //通过比例压缩 float scale = 0.5f; //通过固定长度压缩 /*int dowithheight = 100; int dowithwidth = 300;*/ //压缩之后的长度和宽度 int dowithheight = (int) (scale * height); int dowithwidth = (int) (scale * width); bufferedimage finalimage = new bufferedimage(dowithwidth, dowithheight, bufferedimage.type_int_rgb); finalimage.getgraphics().drawimage(templateimage.getscaledinstance(dowithwidth, dowithheight, java.awt.image.scale_smooth), 0, 0, null); //图片输出路径,以及图片名 fileoutputstream fileoutputstream = new fileoutputstream("f:/temp/linghuafterdowith.jpg"); jpegimageencoder encoder = jpegcodec.createjpegencoder(fileoutputstream); encoder.encode(finalimage); fileoutputstream.close(); } catch (ioexception e) { e.printstacktrace(); } }}
以上就是java如何实现压缩图片大小的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录