Java 图片缩放类ImgUtils

2023-12-16 10:02:01

功能

放大、缩小、设置周边留白

代码

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();
            }
        }
	}
}

文章来源:https://blog.csdn.net/kael_wyh/article/details/135020560
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。