一、前言

    在工作中,难免遇到各种各样的问题,每个人似乎都有一套自己的解决方案。而我,又不想每次解决完问题就把东西扔了,捡了芝麻,丢了西瓜,什么时候才能进步勒?学习要靠积累,毕竟量变才能引起质变嘛。所以写了这篇博文,不定时更新自己项目中遇到的问题、踩过的那些坑......

二、项目

1、文件流

java 将两张图片合成一张图片

开发工具类
    /**
     * 图片合并
     */
    public String joinImage(String url1, String url2) {
        try (InputStream is1 = getImgConn(url1);
             InputStream is2 = getImgConn(url2)) {
            BufferedImage image1 = ImageIO.read(is1);
            BufferedImage image2 = ImageIO.read(is2);
            BufferedImage combined = new BufferedImage(image1.getWidth() * 2, image1.getHeight(), BufferedImage.TYPE_INT_RGB);
            Graphics g = combined.getGraphics();
            g.drawImage(image1, 0, 0, null);
            g.drawImage(image2, image1.getWidth(), 0, null);
            String imgURL = System.currentTimeMillis() + ".jpg";
            ImageIO.write(combined, "JPG", new File("/home/picFiles", imgURL));
            return "/home/picFiles/" + imgURL;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //读文件
    private InputStream getImgConn(String url) {
        try {
            URL url1 = new URL(url);
            URLConnection urlConnection = url1.openConnection();
            InputStream is1 = urlConnection.getInputStream();
            //先读入内存
            ByteArrayOutputStream buf = new ByteArrayOutputStream(8192);
            byte[] b = new byte[1024];
            int len;
            while ((len = is1.read(b)) != -1) {
                buf.write(b, 0, len);
            }
            is1 = new ByteArrayInputStream(buf.toByteArray());
            return is1;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
View Code

相关文章: