Java实现图像处理

在Java中,图片处理可以通过java.awtjavax.imageio库来完成,java.awt是 Java 标准库(Java Standard Edition, JSE)的一部分。

图片缩放

    /**
     * 图片缩放
     * @param originalImage 原始图片
     * @param targetWidth 目标宽度
     * @param targetHeight 目标高度
     * @return 目标图片
     */
    private static BufferedImage scaleImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
        BufferedImage scaledImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = scaledImage.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.drawImage(originalImage, 0, 0, targetWidth, targetHeight, null);
        // 释放资源
        g2d.dispose();
        return scaledImage;
    }

图片裁剪

    /**
     * 图片裁剪
     * @param originalImage 原始图片
     * @param aspectRatio 长宽比
     * @return 目标图片
     */
    private static BufferedImage cropImage(BufferedImage originalImage, float aspectRatio) {
        int x = 0;
        int y = 0;
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();
        int newWidth = (int) (height*aspectRatio);
        int newX = (width-newWidth)/2;
        if (newX > 0) {
            x = newX;
            width = newWidth;
        }
        else {
            int newHeight = (int) (width/aspectRatio);
            y = (height-newHeight)/2;
            height = newHeight;
        }
        return originalImage.getSubimage(x, y, width, height);
    }

图片合并

    /**
     * 图片合并
     * @param image1 图片1
     * @param image2 图片2
     * @return 生成图片
     */
    public static BufferedImage joinImage(BufferedImage image1, BufferedImage image2, int x, int y) {
        // 创建结果图像,大小与缩放后的image1相同
        BufferedImage combinedImage = new BufferedImage(image1.getWidth(), image1.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = combinedImage.createGraphics();
        // 在指定位置绘制第二张图片
        g2d.drawImage(image1, 0, 0, null);
        // 绘制第一张图片
        g2d.drawImage(image2, x, y, null);
        // 释放资源
        g2d.dispose();
        return combinedImage;
    }

从文件读取图像

File imageFile = new File(path);
BufferedImage image = ImageIO.read(imageFile);

将图片保存成文件

File outputFile = new File(path);
ImageIO.write(image, "png", outputFile);

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值