java将两张图片合成

将两张图片合成一张新的图片

    /**
     * 图片合成
     *
     * @param backgroundPath 底图
     * @param smallPath      小图
     * @param type           生成图片类型jpg,png...
     * @param resultPath     生成图片保存路径
     */
    public static void image(String backgroundPath, String smallPath, String type, String resultPath) {
        try {
            Assert.hasText(backgroundPath, "底图路径为空");
            Assert.hasText(smallPath, "小图路径为空");
            BufferedImage small = getBufferedImageFromUrl(smallPath);
            BufferedImage image = getBufferedImageFromUrl(backgroundPath);
            //生成画笔
            Graphics g = image.getGraphics();
            g.drawImage(small, 230, 600,
                    small.getWidth()*2, small.getHeight()*2, null);
            ImageIO.write(image, type, new File(resultPath));
        } catch (IOException e) {
            throw new RuntimeException("合成图片失败", e);
        }

    /**
     * 根据图片url获取图片
     *
     * @param url
     * @return
     * @throws IOException
     */
    private static BufferedImage getBufferedImageFromUrl(String url) throws IOException {
        if (url.startsWith("https://") || url.startsWith("http://")) {
            return ImageIO.read(new URL(url));
        } else {
            return ImageIO.read(new File(url));
        }
    }

测试类

    public static void main(String[] args) {
        image("xxx", "xxx", "png", "xxx");
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。