Java图片添加水印

更新点

考拉博客

  • 文章发布增加首页背景图片
  • 图片增加文本水印,根据图片大小自动设置水印字体大小

Java增加水印代码

/**
 * Created by march on 2018/6/27.
 * 图片工具类
 */

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import javax.imageio.ImageIO;
import java.awt.Color;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImageUtils {
    public static int MIN_FONT_SIZE = 15; //最小字体大小
    public static int REDUCE_SCALE = 20;  //文字虽小比例,根据图片大小进行动态设置字体大小
    public static String MARK_TEXT = "http://kooola.com";
    public static String FONT_NAME = "华为楷体";
    public static int FONT_STYLE = 5;
    private static Color TEXT_COLOR = Color.GRAY;


    /**
     *
//   * @param text  文本
     * @param img 目标图标path
//   * @param fontName 字体名称
//   * @param fontStyle 字体样式
     */
    public static void makeWatermark(String img){
        int fontSize = 40;


        File file = new File(img);
        Image src = null;
        try{
            src = ImageIO.read(file);
        }catch (Exception e){
            e.printStackTrace();
        }
        int width = src.getWidth(null);
        int height = src.getHeight(null);

        int size = width > height ? height : width;
        //根据图片大小动态设置字体大小
        fontSize = size / REDUCE_SCALE < MIN_FONT_SIZE ? MIN_FONT_SIZE : size / REDUCE_SCALE;


        // x,y 为文字开始的相对位置
//        int x = width - fontSize * text.length();
        int x = 0;  //x 设置到左下角开头
        int y = height - fontSize;


        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.createGraphics();
        graphics.drawImage(src, 0, 0, width, height, null);
        graphics.setFont(new Font(FONT_NAME, FONT_STYLE, fontSize));
        graphics.setColor(TEXT_COLOR);
        graphics.drawString(MARK_TEXT, x, y);

        graphics.dispose();
        FileOutputStream fileOutputStream = null;
        try{
            fileOutputStream = new FileOutputStream(img);
        }catch (Exception e){
            e.printStackTrace();
        }
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fileOutputStream);
        try{
            encoder.encode(image);
        }catch (Exception e){
            e.printStackTrace();
        }
        try {
            fileOutputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static void main(String[] args){
        makeWatermark("/Users/march/Downloads/t9gg6570quh5koe6fqkdil2sqm.jpg");
    }
}

效果

Java图片水印

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值