文章目录

  • 前言
  • 一、主要的步骤有哪些?
  • 二、主要代码
  • 1.指定图片大小
  • 2.将照片进行裁剪
  • 3.把上传图片与模板图片进行替换
  • 4.将替换好的新图片进行裁剪
  • 5.生成静态html
  • 总结



前言

之前有一个项目中有一个功能是将一张图片作为基础,将其中的内容进行替换,然后在生成为新的图片,将其进行剪切,并生成到html中。现在有时间将它记录下来。


一、主要的步骤有哪些?

  • 制定上传照片的大小
  • 将照片进行裁剪
  • 把上传图片与模板图片进行替换
  • 将替换好的新图片进行裁剪
  • 生成静态html


二、主要代码

1.指定图片大小

代码如下(示例):

public static void resizeImageByList(List<DataRow> imagePathList) {
        FileOutputStream outputStream = null;
        try {
            String str = MyProps.class.getMethod("getFilepath") + "/" + DateTimeUtil.getNowTimeStr() + ".png";
            logger.debug(str);
            //读入文件
            for (DataRow dataRow:imagePathList) {
            File file = new File(dataRow.getString("iamgeSrc"));
            // 构造Image对象
            BufferedImage src = javax.imageio.ImageIO.read(file);
            // 放大边长
            BufferedImage tag = new BufferedImage(dataRow.getInt("width"), dataRow.getInt("height"), BufferedImage.TYPE_INT_RGB);
            //绘制放大后的图片
            tag.getGraphics().drawImage(src, 0, 0, dataRow.getInt("width"), dataRow.getInt("height"), null);
            outputStream = new FileOutputStream(dataRow.getString("imageDest"));
            ImageIO.write(tag, "png", outputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2.将照片进行裁剪

代码如下(示例):

public static BufferedImage cutHeadImages(String headUrl,String toPath) {
        BufferedImage avatarImage = null;
        try {
            avatarImage = ImageIO.read(new File(headUrl));
//            avatarImage = scaleByPercentage(avatarImage, avatarImage.getWidth(),  avatarImage.getWidth());
            int width = avatarImage.getWidth();
            // 透明底的图片
            BufferedImage formatAvatarImage = new BufferedImage(width, width, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D graphics = formatAvatarImage.createGraphics();
            //把图片切成一个园
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            //留一个像素的空白区域,这个很重要,画圆的时候把这个覆盖
            int border = 1;
            //图片是一个圆型
            Ellipse2D.Double shape = new Ellipse2D.Double(border, border, width - border * 2, width - border * 2);
            //需要保留的区域
            graphics.setClip(shape);
            graphics.drawImage(avatarImage, border, border, width - border * 2, width - border * 2, null);
            graphics.dispose();
            //在圆图外面再画一个圆
            //新创建一个graphics,这样画的圆不会有锯齿
            graphics = formatAvatarImage.createGraphics();
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            int border1 = 3;
            //画笔是4.5个像素,BasicStroke的使用可以查看下面的参考文档
            //使画笔时基本会像外延伸一定像素,具体可以自己使用的时候测试
            Stroke s = new BasicStroke(5F, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
            graphics.setStroke(s);
            graphics.setColor(Color.WHITE);
            graphics.drawOval(border1, border1, width - border1 * 2, width - border1 * 2);
            graphics.dispose();
            OutputStream os = new FileOutputStream(toPath);//发布项目时,如:Tomcat 他会在服务器本地tomcat webapps文件下创建此文件名
            ImageIO.write(formatAvatarImage, "PNG", os);
            return formatAvatarImage;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

3.把上传图片与模板图片进行替换

代码如下(示例):

public static void mergeBothImageCenterByImageList(String negativeImagePath, List<DataRow> additionImagePathList, String imagePathDest ) {
        FileOutputStream outputStream = null;
        try {
            File file = new File(negativeImagePath);
            BufferedImage negativeBufferImge = ImageIO.read(file);
            logger.debug(file.getName());
            logger.debug(file.getPath());
            logger.debug(file.getAbsolutePath());
            logger.debug(file.getCanonicalPath());
            for (DataRow dataRow:additionImagePathList) {
                BufferedImage additionBufferImage = ImageIO.read(new File(dataRow.getString("imagePath")));
                /**
                 *additionImagePath 绘制在 negativeImagePath 上的 任意位置
                 */
                negativeBufferImge.getGraphics().drawImage(additionBufferImage, dataRow.getInt("x"), dataRow.getInt("y"), null);
            }
            outputStream = new FileOutputStream(imagePathDest);
            /**
             * 输出到文件
             */
            ImageIO.write(negativeBufferImge, "png", outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

4.将替换好的新图片进行裁剪

代码如下(示例):

public  List<DataRow> cutImage(String ing) throws IOException {
//        获取图片大小
        File file = new File(ing);
        BufferedImage image = ImageIO.read(file);
        int width = image.getWidth();
        int height = image.getHeight();
//        剪切次数
        int count=0;
//        判断时候够高度
        boolean test = true;

        if(height%200==0){
            count=height/200;
        }else{
            count=(height/200)+1;
            test=false;
        }

        List<DataRow> imageList=new ArrayList<>();
        FileOutputStream fos = null;
        for (int i=0;i<count;i++){
            if(i==count-1&&!test){
//                截切图片
                BufferedImage bufferedImage = OperateImage.cropImage(image, 0, 200*i, 750, height);
                String name =DateTimeUtil.getNowTimeStr()+ i + ".png";
                try {
                    fos = new FileOutputStream(myProps.getFilepath() + "/testimage/" +name);
                    ImageIO.write(bufferedImage,"png", fos);
                    fos.flush();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                DataRow imagedata= new DataRow();
                imagedata.put("url","http://"+myProps.getDomainurl()+ "/image/testimage/"+name);
                imageList.add(imagedata);
            }else{
//                截切图片
                String name =DateTimeUtil.getNowTimeStr()+ i + ".png";
                BufferedImage bufferedImage = OperateImage.cropImage(image, 0, 200*i, 750, (i+1)*200);
                try {
                    fos = new FileOutputStream(myProps.getFilepath() + "/testimage/"+name);
                    ImageIO.write(bufferedImage,"png", fos);
                    fos.flush();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                DataRow imagedata= new DataRow();
                imagedata.put("url","http://"+myProps.getDomainurl()+ "/image/testimage/"+name);
                imageList.add(imagedata);
            }
        }
        fos.close();
        return imageList;
    }

5.生成静态html

代码如下(示例):

public String insActiveArrticle(List<DataRow> imageList) throws IOException {
        //创建模版加载器
        ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
        resolver.setPrefix("/templates/template/");  //模板文件的所在目录
        resolver.setSuffix(".html");       //模板文件后缀
        //创建模板引擎
        TemplateEngine templateEngine = new TemplateEngine();
        //将加载器放入模板引擎
        templateEngine.setTemplateResolver(resolver);
        //创建字符输出流并且自定义输出文件的位置和文件名
        String name= DateTimeUtil.getNowTimeStr() +".html";
//        String name=myProps.getFilepath()+"/article/测试1.html";
        FileWriter writer = new FileWriter(myProps.getFilepath()+"/article/"+name);
        //创建Context对象(存放Model)
        Context context = new Context();
        //放入数据
        context.setVariable("imageList",imageList);
        //创建静态文件,"text"是模板html名字
        templateEngine.process("test",context,writer);
        return name;
    }

效果图就不展示了。


总结

不是很难,希望对大家有所帮助。