100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 图片太大_图片太大?手把手教你如何用java实现一个高质量图片压缩程序

图片太大_图片太大?手把手教你如何用java实现一个高质量图片压缩程序

时间:2020-11-08 15:22:08

相关推荐

图片太大_图片太大?手把手教你如何用java实现一个高质量图片压缩程序

使用java几十行代码实现一个高质量图片压缩程序,再也不用去自己找网络的压缩程序啦!而且很多网上的工具还有水印或者其他的限制,自己动手写一个简单的应用,是再合适不过了。

一、实现原理

1、声明两个字符串变量,分别是要压缩图片的路径和压缩后图片的存放路径

private String brfore_image_path = "D:01.jpg";private String after_image_path = "D:emp";

2、利用字符串的方法lastIndexOf,找到和.最后出现的位置,目的是匹配到图片文件名。

int begin = brfore_image_path.lastIndexOf("");int end = brfore_image_path.lastIndexOf(".");String image_name=brfore_image_path.substring(begin+1,end);

3、创建BufferedImage对象来读取需要压缩的图片

4、获取原始图片的一系列参数

int in_width = bi.getWidth();//图宽int in_height = bi.getHeight();//图高int in_minx = bi.getMinX();//BufferedImage的最小xint in_miny = bi.getMinY();//BufferedImage的最小yint type = bi.getType();//返回图像类型int out_width = in_width;//要输出图像的宽int out_height = in_height;//要输出图像的高int multiple = 1;//系数

5、压缩核心代码,可自己调试找最适合的临界值,我选取的是大于1000000像素点时就压缩一半

while(out_width * out_height > 1000000){ out_width = out_width/2; out_height = out_height/2; multiple = multiple * 2;}

6、创建新的BufferedImage对象,把新的参数传进去,并根据系数把一个个像素点写进图片。

for(int i=0;i

7、把新的BufferedImage对象写到你要保存压缩图片的地址就好了。

二、完整代码

public class CompressImage { private String brfore_image_path = "D:01.jpg"; private String after_image_path = "D:emp"; public CompressImage(){ } public void get_image(){ int begin = brfore_image_path.lastIndexOf(""); int end = brfore_image_path.lastIndexOf("."); String image_name = brfore_image_path.substring(begin+1,end); File in_file = new File(brfore_image_path); BufferedImage bi = null; try { bi = ImageIO.read(in_file); }catch(Exception e) { e.printStackTrace(); } int in_width = bi.getWidth(); int in_height = bi.getHeight(); int in_minx = bi.getMinX(); int in_miny = bi.getMinY(); int type = bi.getType(); int out_width = in_width; int out_height = in_height; int multiple = 1; //具体的值可调 while(out_width * out_height > 1000000){ out_width = out_width/2; out_height = out_height/2; multiple = multiple * 2; } BufferedImage out_image_martrix = new BufferedImage(out_width, out_height, type); for(int i=0;i

三、总结

代码挺简单的,但是自己动手实现完成一个小功能也不一样哦,而且我觉得压缩的质量还挺高的,所以把自己的实现思路和代码分享出来。有兴趣的童鞋可以自己复制上面的完整代码,只要改成自己的路径就可以运行了。

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