java多圖合成加文字描述

2中方式:
目的將現有的幾張圖片及文字描述通過BufferedImage合成一張圖片
2種方式都可以實現,相對來說第二種更好一點圖片失真度可以忽略,第一種會有失真情況

直接上代碼(本地文件地址需要自己改動)
第一種方式:


import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;

import java.io.File;
import java.io.IOException;
import java.text.AttributedString;
import java.text.ParseException;

public class shareImg {

    public static void main(String[] args) throws ParseException, IOException {
        String templatePath = "C:/Users/Administrator/Desktop/迪奧2/";
        String templateImg = templatePath + "temp.png";

        String mainImg = templatePath + "1.jpg";
        String outPath = templatePath + "res.jpg";
        String moneyContent = "搶購價:" ;
        String goodsMoneyContent =  "¥996";
        String priceMoneyContent =  "¥1152";
        String typeContent = "立即購買";
        String typeContentB = "限時特賣";

        try {
            templateImgAddQRcodeImgAndText(templateImg, mainImg, moneyContent, outPath, typeContent, typeContentB,goodsMoneyContent,priceMoneyContent);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 合成圖片
     * @param templateImgPath 模板圖片
     * @param mainImg 主圖拼接圖
     * @param moneyContent 現價
     * @param toPath 保存奔赴位置
     * @param contentText1
     * @param contentText2
     * @param goodsMoneyContent
     * @param priceMoneyContent
     * @throws IOException
     */
    public static void templateImgAddQRcodeImgAndText(String templateImgPath, String mainImg, String moneyContent,
                                                      String toPath, String contentText1, String contentText2,String goodsMoneyContent,String priceMoneyContent) throws IOException {
        //讀取模板圖
        BufferedImage template = ImageIO.read(new File(templateImgPath));
        //模板寬高
        int width = template.getWidth();
        int height = template.getHeight();
        //主圖片
        BufferedImage groupImg = ImageIO.read(new File(mainImg));




        //創建畫布 --以模板圖的寬高做畫布大小
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //創建畫筆
        Graphics2D g = img.createGraphics();
        //設置畫板背景顏色
        g.setBackground(new Color(255, 255, 255, 255));
        //去除邊框
        g.fillRect(0,0,width, height);
        //統一對文字去除鋸齒邊框
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        //載入模板 -- getScaledInstance方法可以保持圖片改變大小不是太失真
        g.drawImage(template.getScaledInstance(width,height, Image.SCALE_SMOOTH), 0, 0, width, height, null);
        //商品主圖位置 6 - 6 代表x,y 軸的距離
        g.drawImage(groupImg.getScaledInstance(252,252, Image.SCALE_SMOOTH), 6, 6, 252,252,  null);

        if (contentText1 != null) {
//            字體 / 粗細 / 大小
            Font font = new Font("宋體", Font.BOLD , 22);

            //設置字體及顏色
            Color color = new Color(255, 255, 255);
            g.setColor(color);
            g.setFont(font);
            //文字所在模板位置
            g.drawString(contentText1, 291, 231);
        }

        if (contentText1 != null) {
//            字體 / 粗細 / 大小
            Font font = new Font("蘋方", Font.BOLD , 22);

            //設置字體及顏色
            Color color = new Color(255, 31, 9);
            g.setColor(color);
            g.setFont(font);
            //文字所在模板位置
            g.drawString(contentText1, 291, 200);
        }



        if (contentText2 != null) {
            Font font = new Font("微軟雅黑", Font.BOLD , 30);
            Color color = new Color(255,255,255);
            g.setColor(color);
            g.setFont(font);
            g.drawString(contentText2, 215, 314);
        }
        if (moneyContent != null) {
            Font font = new Font("蘋方 粗體", Font.BOLD, 22);
            Color color = new Color(51,51,51);
            g.setColor(color);
            g.setFont(font);
            g.drawString(moneyContent, 266, 80);
        }
        if (goodsMoneyContent != null) {
            Font font = new Font("微軟雅黑", Font.BOLD, 34);
            Color color = new Color(255,80,0);
            g.setColor(color);
            g.setFont(font);
            g.drawString(goodsMoneyContent, 266, 120);
        }
        if (priceMoneyContent != null) {
            Font font = new Font("蘋方 粗體", Font.BOLD, 22);
            Color color = new Color(153,153,153 );
            g.setColor(color);

            //給文字加刪除線
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            AttributedString as = new AttributedString(priceMoneyContent);
            as.addAttribute(TextAttribute.FONT, font);
            as.addAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON, 0, priceMoneyContent.length());
            g.drawString(as.getIterator(), 266, 150);
        }
        g.dispose();
        //寫入本地位置
        ImageIO.write(img, "jpg", new File(toPath));
    }
}

第二種方式:



import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.AttributedString;


public class Test {


    public static String overlapImage(String backgroundPath, String frontgroudPath, String goodsMoneyContent, String priceMoneyContent, String outPutPath
            ,String moneyContent,String contentText1,String contentText2) {
        try {

			/**
             * 設置文字字體(具體看方法,路徑位置需要有這種字體)
             */
            Font font = getFont("1");
            Font font2 = getFont("2");
            Font font3 = getFont("3");

            Font pinfang_h_42 = font3.deriveFont(Font.PLAIN, 42);
            Font pinfang_h_22 = font3.deriveFont(Font.PLAIN, 22);
            Font pinfang_h_30 = font3.deriveFont(Font.PLAIN, 30);

            Font pinfang_m_42 = font3.deriveFont(Font.PLAIN, 42);
            Font pinfang_m_22 = font3.deriveFont(Font.PLAIN, 22);
            Font pinfang_m_30 = font3.deriveFont(Font.PLAIN, 30);

            Font pinfang_30 = font.deriveFont(Font.PLAIN, 30);
            Font pinfang_42 = font.deriveFont(Font.PLAIN, 42);
            Font pinfang_22 = font.deriveFont(Font.PLAIN, 22);
//            Font pinfang_42 = new Font("PingFang Regular", Font.PLAIN, 42);
//            Font pinfang_22 = new Font("PingFang Regular", Font.PLAIN, 22);
//            Font pinfang_30 = new Font("PingFang Regular", Font.PLAIN, 30);

            //設置圖片大小
            BufferedImage background = resizeImagePng(420, 336, ImageIO.read(new File(backgroundPath)));
            BufferedImage frontgroud = resizeImagePng(252, 252, ImageIO.read(new File(frontgroudPath)));

            //在背景圖片中添加入需要寫入的信息,
            Graphics2D g = background.createGraphics();
            //統一對文字去除鋸齒邊框
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            //設置爲透明覆蓋
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1.0f));
            //在背景圖片上相框
            g.drawImage(frontgroud, 6, 8, frontgroud.getWidth(), frontgroud.getHeight(), null);

            if (contentText1 != null) {
//            字體 / 粗細 / 大小
//                Font font = new Font("宋體", Font.BOLD , 22);

                //設置字體及顏色
                Color color = new Color(255, 255, 255);
                g.setColor(color);
                g.setFont(pinfang_h_22);
//                AttributedString as2 = new AttributedString(contentText1);
//                as2.addAttribute(TextAttribute.FONT, pinfang_42);
                g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                //文字所在模板位置
                g.drawString(contentText1, 294, 232);
            }
            if (contentText2 != null) {
//            字體 / 粗細 / 大小
//                Font font = new Font("蘋方", Font.BOLD , 22);

                //設置字體及顏色
                Color color = new Color(255, 255, 255);
                g.setColor(color);
//                g.setFont(pinfang_30);
                g.setFont(pinfang_m_30);
//                AttributedString as2 = new AttributedString(contentText2);
//                as2.addAttribute(TextAttribute.FONT, pinfang_22);
                //文字所在模板位置
                g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                g.drawString(contentText2, 215, 313);
            }
            if (moneyContent != null) {
//                Font font = new Font("蘋方 粗體", Font.BOLD, 22);
                Color color = new Color(51,51,51);
                g.setColor(color);
                g.setFont(pinfang_22);
//                AttributedString as2 = new AttributedString(moneyContent);
//                as2.addAttribute(TextAttribute.FONT, pinfang_22);
                g.drawString(moneyContent, 266, 90);
            }
            if (goodsMoneyContent != null) {
//                Font font = new Font("微軟雅黑", Font.BOLD, 34);
                Color color = new Color(255,80,0);
                g.setColor(color);
                g.setFont(pinfang_h_42);
//                AttributedString as2 = new AttributedString(goodsMoneyContent);
//                as2.addAttribute(TextAttribute.FONT, pinfang_42);


                g.drawString(goodsMoneyContent, 266, 135);
            }
            if (priceMoneyContent != null) {
//                Font font = new Font("蘋方 粗體", Font.BOLD, 22);
                Color color = new Color(153,153,153 );
                g.setColor(color);

                /*//給文字加刪除線
                g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);*/
                AttributedString as = new AttributedString(priceMoneyContent);
//                as.addAttribute(TextAttribute.FONT, font);
                as.addAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON, 0, priceMoneyContent.length());
                as.addAttribute(TextAttribute.FONT, pinfang_22);
                g.drawString(as.getIterator(), 266, 162);
            }
            g.dispose();
            //輸出圖片(png格式,嘗試過jpg,不能用.具體還未研究)
            ImageIO.write(background, "png", new FileOutputStream(outPutPath));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 重定義圖片尺寸
     * @param x
     * @param y
     * @param bfi
     * @return
     */
    public static BufferedImage resizeImagePng(int x, int y, BufferedImage bfi) {
        BufferedImage bufferedImage = new BufferedImage(x, y, BufferedImage.TYPE_INT_ARGB);
        bufferedImage.getGraphics().drawImage(
                bfi.getScaledInstance(x, y, Image.SCALE_SMOOTH), 0, 0, null);
        return bufferedImage;
    }

    public static void main(String[] args) {
        String frontgroudPath = "C:\\Users\\Administrator\\Desktop\\迪奧2\\1.jpg";
        String backgroundPath = "C:\\Users\\Administrator\\Desktop\\迪奧2\\temp.png";
        String goodsMoneyContent = "¥599";
        String priceMoneyContent = "¥1099";
        String moneyContent = "限時價:" ;
        String typeContent = "立即搶購";
        String typeContentB = "限時特賣";
        String outPutPath = "C:\\Users\\Administrator\\Desktop\\迪奧2\\demo2.png";
        overlapImage(backgroundPath, frontgroudPath, goodsMoneyContent, priceMoneyContent, outPutPath,moneyContent,typeContent,typeContentB);
    }


    //filepath字體文件的路徑
    private static Font getFont(String type){
        Font font = null;
        String filepath = "";
        if("1".equals(type)){
            filepath = "C:\\Users\\Administrator\\Desktop\\字體\\PingFang Regular.ttf";
        }else if("2".equals(type)){
            filepath = "C:\\Users\\Administrator\\Desktop\\字體\\PingFang Medium.ttf";
        }else if("3".equals(type)){
            filepath = "C:\\Users\\Administrator\\Desktop\\字體\\PingFang Heavy.ttf";
        }else{
            filepath = "C:\\Users\\Administrator\\Desktop\\字體\\PingFang Regular.ttf";
        }

        File file = new File(filepath);
        try{
            font = Font.createFont(Font.TRUETYPE_FONT, file);
        }catch (FontFormatException e){
            return null;
        }catch (FileNotFoundException e){
            return null;
        }catch (IOException e){
            return null;
        }
        return font;
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章