自学内容网 自学内容网

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


原文地址:https://blog.csdn.net/watson2017/article/details/140376384

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!