使用java程序,对图片的尺寸及格式进行重新设置,需要注意的是,透明背景的图片和非透明背景的图片的处理是不一样的,详情请看代码
package com.ilike.demo;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
* 使用java程序,对图片的尺寸及格式进行重新设置
* 注意:透明背景的图片和非透明背景的图片的处理是不一样的,详情请看代码
*
* @author 桑伟东
*
*/
public class ResetPhoto {
public static void main(String[] args) throws Exception {
File fromFile = new File("D:\\tmp\\h.png");
File toFile = new File("D:\\tmp\\testImage\\h.png");
//resizePhotoForPNG(fromFile, toFile, 0.9, "jpg");
resizeImage(fromFile, toFile, 0.9, "png");
}
/**
* 该方法可以处理任何背景的图片,包括透明背景
* 优点:可以处理透明背景的图片
* 缺点:只能读取png格式的图片,不能跨格式读写,
* 例如读取jpg格式的,无论最后保存成什么格式,都会有问题
*
* @param fromFile
* 数据源(原始图片)
* @param toFile
* 目的地(修改后的图片)
* @param scale
* 缩放比例,例如缩小为原来的80%,scale=0.8
* @param format
* 新图片的格式,如jpg,png
*/
public static void resizePhotoForPNG(File fromFile, File toFile, double scale, String format) {
try {
// 1.读取图片文件,并获得图片缓冲对象
BufferedImage bi2 = ImageIO.read(fromFile);
// 2.读取图片的原始尺寸大小
int oldHeight = bi2.getHeight();
int oldWidth = bi2.getWidth();
// 3.计算图片新的宽高
int newWidth = (int) (oldWidth * scale);
int newHeight = (int) (oldHeight * scale);
BufferedImage to = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = to.createGraphics();
to = g2d.getDeviceConfiguration().createCompatibleImage(newWidth, newHeight, Transparency.TRANSLUCENT);
g2d.dispose();
g2d = to.createGraphics();
@SuppressWarnings("static-access")
Image from = bi2.getScaledInstance(newWidth, newHeight, bi2.SCALE_AREA_AVERAGING);
g2d.drawImage(from, 0, 0, null);
g2d.dispose();
ImageIO.write(to, format, toFile);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 该方法可以处理任何格式的非透明背景的图片,对于非透明背景的图片,
* 跨格式读写也没有问题,但是对于透明格式的图片,不跨格式,也会有问题
* 优点:可以跨格式读写图片,例如读取jpg格式的,无论最后保存成什么格式,只要背景不透明都没有问题
* 缺点:不能读写透明背景的图片
*
* @param fromFile
* 数据源(原始图片)
* @param toFile
* 目的地(修改后的图片)
* @param scale
* 缩放比例,例如缩小为原来的80%,scale=0.8
* @param format
* 新图片的格式,如jpg,png
*/
public static void resizeImage(File fromFile, File toFile, double scale, String format) throws IOException {
try {
// 1.读取图片文件,并获得图片缓冲对象
BufferedImage bi2 = ImageIO.read(fromFile);
// 2.读取图片的原始尺寸大小
int oldHeight = bi2.getHeight();
int oldWidth = bi2.getWidth();
// 3.计算图片新的宽高
int newWidth = (int) (oldWidth * scale);
int newHeight = (int) (oldHeight * scale);
BufferedImage image = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_BGR);
Graphics graphics = image.createGraphics();
graphics.drawImage(bi2, 0, 0, newWidth, newHeight, null);
ImageIO.write(image, format, toFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}