Java图像处理工具类:实现图像缩放

使用Java实现一个简单的图像处理工具类,可完成图像安装一定比例缩放,代码如下:

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 图像缩放工具类
 */
public class ImageUtils {
    /**
     * 缩放图像
     *
     * @param src   原始图像
     * @param scale 缩放比例
     * @return
     */
    public static BufferedImage zoomByScale(BufferedImage src, double scale) {
        //获取缩放后的长和宽
        int width = (int) (scale * src.getWidth());
        int height = (int) (scale * src.getHeight());
        Image instance = src.getScaledInstance(width, height, Image.SCALE_DEFAULT);
        //新建一个和Image对象相同大小的画布
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //获取画笔
        Graphics2D graphics = image.createGraphics();
        //将Image对象画在画布上,最后一个参数,ImageObserver:接收有关 Image 信息通知的异步更新接口,没用到直接传空
        graphics.drawImage(instance, 0, 0, null);
        //释放资源
        graphics.dispose();
        return image;
    }

    /**
     * 缩放图像,并保存至特定路径
     *
     * @param src    原始图像路径
     * @param dest   缩放图像路径
     * @param format 缩放图像格式
     * @param scale  缩放比例
     * @throws IOException
     */
    public static void zoomByScale(String src, String dest, String format, double scale) throws IOException {
        BufferedImage srcImg = ImageIO.read(new File(src));
        int width = (int) (scale * srcImg.getWidth());
        int height = (int) (scale * srcImg.getHeight());
        Image instance = srcImg.getScaledInstance(width, height, Image.SCALE_DEFAULT);
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = image.createGraphics();
        graphics.drawImage(instance, 0, 0, null);
        graphics.dispose();
        ImageIO.write(image, format, new FileOutputStream(new File(dest)));
    }

    public static void main(String[] args) throws IOException {
        //缩小
        BufferedImage src = ImageIO.read(new File("E:/image/1.jpg"));
        BufferedImage image = zoomByScale(src, 0.6);
        //图像处理
//        image.getHeight();
        //另存
        ImageIO.write(image, "jpg", new FileOutputStream(new File("E:/image/1-1.jpg")));

        //放大图片
        zoomByScale("E:/image/1.jpg", "E:/image/1-2.jpg", "jpg", 1.2);
    }
}

测试效果
Java图像处理工具类:实现图像缩放_第1张图片
Java图像处理工具类:实现图像缩放_第2张图片

你可能感兴趣的:(图像检索,Java)