java在图片上写文字

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xingxiupaioxue/article/details/82109963

网上很多需要用到codec.jpeg.JPEGImageEncoder;类而这个类是过时的类,经常失败加载不成功,遂换成ImageIO.write测试可用

public class WaterMarkUtils {
        public static void main(String[] args) {
             String filePath = "d:\\icaw-log\\20170611002000_0.jpg";
                String outPath = "d:\\icaw-log\\222.jpg";
                drawTextInImg(filePath, outPath, new FontText("中国", 6, "#B80000", 40, "微软雅黑"));

        }
          
        public static void drawTextInImg(String filePath,String outPath, FontText text) {
            ImageIcon imgIcon = new ImageIcon(filePath);
            Image img = imgIcon.getImage();
            int width = img.getWidth(null);
            int height = img.getHeight(null);
            BufferedImage bimage = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bimage.createGraphics();
            g.setColor(getColor(text.getWm_text_color()));
            g.setBackground(Color.white);
            g.drawImage(img, 0, 0, null);
            Font font = null;
            font = new Font(null, Font.BOLD, text.getWm_text_size());
            g.setFont(font);
            g.drawString(text.getText(), 3*width/4, height/10);
            g.dispose();

            try {
                FileOutputStream out = new FileOutputStream(outPath);
                ImageIO.write(bimage, "JPEG", out);
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // color #2395439
        public static Color getColor(String color) {
            if (color.charAt(0) == '#') {
                color = color.substring(1);
            }
            if (color.length() != 6) {
                return null;
            }
            try {
                int r = Integer.parseInt(color.substring(0, 2), 16);
                int g = Integer.parseInt(color.substring(2, 4), 16);
                int b = Integer.parseInt(color.substring(4), 16);
                return new Color(r, g, b);
            } catch (NumberFormatException nfe) {
                return null;
            }
        }
}
 

猜你喜欢

转载自blog.csdn.net/xingxiupaioxue/article/details/82109963