「java等比压缩图片」JAVA 图片压缩

博主:adminadmin 2022-12-01 01:56:06 80

本篇文章给大家谈谈java等比压缩图片,以及JAVA 图片压缩对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

java如何实现把一个大图片压缩到指定大小的图片且长宽比不变

也就是图片压缩,可以不修改任何大小的压缩(速度快),也可等比例修改大小压缩(较慢)

下面这是一段等比例缩小图片的方法。

public String compressPic(String inputDir, String outputDir,

String inputFileName, String outputFileName, int width,

int height, boolean gp,String hzm) {

try {

if (!image.exists()) {

return "";

}

Image img = ImageIO.read(image);

// 判断图片格式是否正确

if (img.getWidth(null) == -1) {

return "no";

} else {

int newWidth; int newHeight;

// 判断是否是等比缩放

if (gp == true) {

// 为等比缩放计算输出的图片宽度及高度

double rate1 = ((double) img.getWidth(null)) / (double) width ;

double rate2 = ((double) img.getHeight(null)) / (double) height ;

// 根据缩放比率大的进行缩放控制

double rate = rate1 rate2 ? rate1 : rate2;

newWidth = (int) (((double) img.getWidth(null)) / rate);

newHeight = (int) (((double) img.getHeight(null)) / rate);

} else {

newWidth = img.getWidth(null); // 输出的图片宽度

newHeight = img.getHeight(null); // 输出的图片高度

}

BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);

/*

* Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的

* 优先级比速度高 生成的图片质量比较好 但速度慢

*/

Image im = img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);

tag.getGraphics().drawImage(im, 0, 0, null);

FileOutputStream out = new FileOutputStream(outputDir + outputFileName);

//JPEGImageEncoder可适用于其他图片类型的转换

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

encoder.encode(tag);

out.close();

}

} catch (IOException ex) {

ex.printStackTrace();

}

return "ok";

}

java是怎么实现等比例缩小图片而不失真的啊?

按照等比例的长宽进行缩放就可以了呀,就好像你打开一个图片,一般都有缩放功能,原理是一样的,等比例的缩放,关键像素还是存在的。

java将图片按比例缩小

Image srcImg = ImageIO.read(new FileInputStream(fnSrc) );//取源图

int width = 600; //假设要缩小到600点像素

int height = srcImg.getHeight(null)*600/srcImg.getWidth(null);//按比例,将高度缩减

System.out.println("Width: "+srcImg.getWidth(null));// 这几行是调试用

System.out.println("Height: "+srcImg.getHeight(null));

System.out.println("Width2: "+width);

System.out.println("Height2: "+height);

Image smallImg =srcImg.getScaledInstance(width, height, Image.SCALE_SMOOTH);//缩小

java等比压缩图片的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于JAVA 图片压缩、java等比压缩图片的信息别忘了在本站进行查找喔。

The End

发布于:2022-12-01,除非注明,否则均为首码项目网原创文章,转载请注明出处。