
使用 java 几十行代码实现一个高质量图片压缩程序,再也不用去自己找网络的压缩程序啦!而且很多网上的工具还有水印或者其他的限制,自己动手写一个简单的应用,是再合适不过了。
一、实现原理
1、声明两个 字符串 变量,分别是要压缩图片的路径和压缩后图片的存放路径
private String brfore_image_path = "D:1.jpg"; private String after_image_path = "D:temp";
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的最小x
int in_miny = bi.getMinY();//BufferedImage的最小y
int 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<out_width;i++) { for(int j =0;j<out_height;j++) { intpixel=bi.getRGB(i*multiple+in_minx,j*multiple+in_miny); ut_image_martrix.setRGB(i, j, pixel); } }
7、把新的BufferedImage对象写到你要保存压缩图片的地址就好了。
二、完整代码
public class CompressImage { private String brfore_image_path = "D:1.jpg"; private String after_image_path = "D:temp"; 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<out_width;i++) { for(int j =0;j<out_height;j++) { int pixel =bi.getRGB(i*multiple+in_minx, j*multiple+in_miny); out_image_martrix.setRGB(i, j, pixel); } } try{ after_image_path = after_image_path + image_name + ".jpg"; ImageIO.write(out_image_martrix,"jpg", new File(new_path)); bi = null; out_image_martrix = null; }catch(Exception e){ e.printStackTrace(); } } //测试代码 public static void main(String[] args) { new CompressImage().get_image(); } }
三、总结
代码挺简单的,但是自己动手实现完成一个小功能也不一样哦,而且我觉得压缩的质量还挺高的,所以把自己的实现思路和代码分享出来。有兴趣的童鞋可以自己复制上面的完整代码,只要改成自己的路径就可以运行了。