放大、缩小、设置周边留白
package utils;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ImgUtils
{
public static void toFix( String imgPath, int toWidth, int toHeight, String toPath )
{
toFix(imgPath, toWidth, toHeight, toPath, 0);
}
/**
* 缩放图片
* @param imgPath 需要缩放的图片路径
* @param toWidth 缩放后的宽度
* @param toHeight 缩放后的高度
* @param toPath 缩放后的图片保存路径
* @param space 上下左右留白的像素
*/
public static void toFix( String imgPath, int toWidth, int toHeight, String toPath, int space )
{
BufferedImage bufferedImage = null;
File file = new File(imgPath);
if (file.canRead())
{
try
{
bufferedImage = ImageIO.read(file);
int w = bufferedImage.getWidth();
int h = bufferedImage.getHeight();
double sw = (toWidth-space*2) * 1.0 / w;
double sh = (toHeight-space*2) * 1.0 / h;
double scale = Math.min(sw, sh);
w = (int) (w * scale);
h = (int) (h * scale);
int x = (toWidth - w) >> 1;
int y = (toHeight - h) >> 1;
BufferedImage newImage = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_4BYTE_ABGR);
Graphics graphics = newImage.getGraphics();
graphics.drawImage(bufferedImage.getScaledInstance(w, h, BufferedImage.SCALE_SMOOTH), x, y, null);
graphics.dispose();
ImageIO.write(newImage, "png", new File(toPath));
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}