欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java用自带的Image IO给图片添加水印

程序员文章站 2022-06-25 23:27:03
1. 文字水印import sun.font.fontdesignmetrics;import javax.imageio.imageio;import java.awt.*;import java....

1.  文字水印

import sun.font.fontdesignmetrics;
import javax.imageio.imageio;
import java.awt.*;
import java.awt.image.bufferedimage;
import java.io.file;
import java.io.fileoutputstream;
import java.io.ioexception;
/**
 * @author chengjiansheng
 * @date 2021/6/10
 */
public class watermarkutil
{
    public static void main(string[] args) throws ioexception
        {
            addtext("f:/1.jpeg", "我的梦想是成为火影");
        }
        /**
         * 加文字水印
         * @param srcpath   原文件路径
         * @param content   文字内容
         * @throws ioexception
         */
    public static void addtext(string srcpath, string content) throws ioexception
    {
        //  读取原图片信息
        bufferedimage srcimage = imageio.read(new file(srcpath));
        int width = srcimage.getwidth();
        int height = srcimage.getheight();
        //  创建画笔,设置绘图区域
        bufferedimage bufferedimage = new bufferedimage(width, height, bufferedimage.type_int_rgb);
        graphics2d g = bufferedimage.creategraphics();
        g.drawimage(srcimage, 0, 0, width, height, null);
        //        g.drawimage(srcimage.getscaledinstance(width, height, image.scale_smooth), 0, 0, null);
        g.setfont(new font("宋体", font.plain, 32));
        g.setcolor(color.red);
        //  计算文字长度
        int len = g.getfontmetrics(g.getfont()).charswidth(content.tochararray(), 0, content.length());
        fontdesignmetrics metrics = fontdesignmetrics.getmetrics(g.getfont());
        int len2 = metrics.stringwidth(content);
        system.out.println(len);
        system.out.println(len2);
        //  计算文字坐标
        int x = width - len - 10;
        int y = height - 20;
        //        int x = width - 2 * len;
        //        int y = height - 1 * len;
        g.drawstring(content, x, y);
        g.dispose();
        //  输出文件
        fileoutputstream fos = new fileoutputstream("f:/2.png");
        imageio.write(bufferedimage, "png", fos);
        fos.flush();
        fos.close();
    }
}

Java用自带的Image IO给图片添加水印

可以设置文字透明度

 g.setcomposite(alphacomposite.getinstance(alphacomposite.src_atop, 0.8f)); 

2.  旋转文字

import sun.font.fontdesignmetrics;
import javax.imageio.imageio;
import java.awt.*;
import java.awt.geom.affinetransform;
import java.awt.image.bufferedimage;
import java.io.file;
import java.io.fileoutputstream;
import java.io.ioexception;
/**
 * @author chengjiansheng
 * @date 2021/6/10
 */
public class watermarkutil
{
    // 水印透明度
    private static final float alpha = 0.5 f;
    // 水印文字字体
    private static final font font = new font("宋体", font.bold, 30);
    // 水印文字颜色
    private static final color color = color.red;
    public static void main(string[] args) throws ioexception
        {
            addtext("f:/1.jpeg", "图片由木叶村提供,仅供忍者联军使用!");
        }
        /**
         * 加文字水印
         * @param srcpath   原文件路径
         * @param content   文字内容
         * @throws ioexception
         */
    public static void addtext(string srcpath, string content) throws ioexception
    {
        //  读取原图片信息
        bufferedimage srcimage = imageio.read(new file(srcpath));
        int width = srcimage.getwidth();
        int height = srcimage.getheight();
        //  创建画笔,设置绘图区域
        bufferedimage bufferedimage = new bufferedimage(width, height, bufferedimage.type_int_rgb);
        graphics2d g = bufferedimage.creategraphics();
        g.drawimage(srcimage, 0, 0, width, height, null);
        //        g.drawimage(srcimage.getscaledinstance(width, height, image.scale_smooth), 0, 0, null);
        //  旋转文字
        affinetransform affinetransform = g.gettransform();
        affinetransform.rotate(math.toradians(-30), 0, 0);
        font rotatedfont = font.derivefont(affinetransform);
        g.setfont(rotatedfont); // 字体
        g.setcolor(color); // 颜色
        g.setcomposite(alphacomposite.getinstance(alphacomposite.src_atop, alpha)); // 透明度
        //  计算文字长度
        int len = g.getfontmetrics(g.getfont()).charswidth(content.tochararray(), 0, content.length());
        fontdesignmetrics metrics = fontdesignmetrics.getmetrics(g.getfont());
        int len2 = metrics.stringwidth(content);
        system.out.println(len);
        system.out.println(len2);
        //  计算水印文字坐标
        int x = width / 5;
        int y = height / 3 * 2;
        g.drawstring(content, x, y);
        g.dispose();
        //  输出文件
        fileoutputstream fos = new fileoutputstream("f:/2.png");
        imageio.write(bufferedimage, "png", fos);
        fos.flush();
        fos.close();
    }
}

Java用自带的Image IO给图片添加水印

画矩形框

import sun.font.fontdesignmetrics;
import javax.imageio.imageio;
import java.awt.*;
import java.awt.image.bufferedimage;
import java.io.file;
import java.io.fileoutputstream;
import java.io.ioexception;
/**
 * @author chengjiansheng
 * @date 2021/6/10
 */
public class watermarkutil
{
    // 水印透明度
    private static final float alpha = 0.5 f;
    // 水印文字字体
    private static final font font = new font("宋体", font.bold, 30);
    // 水印文字颜色
    private static final color color = color.red;
    public static void main(string[] args) throws ioexception
        {
            addtext("f:/1.jpeg", "图片由木叶村提供,仅供忍者联军使用!");
        }
        /**
         * 加文字水印
         * @param srcpath   原文件路径
         * @param content   文字内容
         * @throws ioexception
         */
    public static void addtext(string srcpath, string content) throws ioexception
    {
        //  读取原图片信息
        bufferedimage srcimage = imageio.read(new file(srcpath));
        int width = srcimage.getwidth();
        int height = srcimage.getheight();
        //  创建画笔,设置绘图区域
        bufferedimage bufferedimage = new bufferedimage(width, height, bufferedimage.type_int_rgb);
        graphics2d g = bufferedimage.creategraphics();
        g.drawimage(srcimage, 0, 0, width, height, null);
        g.setfont(font); // 字体
        g.setcolor(color); // 颜色
        g.setcomposite(alphacomposite.getinstance(alphacomposite.src_atop, alpha)); // 透明度
        //  计算文字宽高度
        fontdesignmetrics metrics = fontdesignmetrics.getmetrics(font);
        int textwidth = metrics.stringwidth(content); //  文字宽度
        int textheight = metrics.getheight(); //  文字高度
        //  计算文字坐标
        int x = (width - textwidth) / 2;
        int y = (height + textheight) / 2;
        //  写文字
        g.drawstring(content, x, y);
        //  画矩形
        int padding = 10; // 内边距
        g.drawrect(x - padding / 2, y - textheight, textwidth + padding, textheight + padding);
        g.dispose();
        //  输出文件
        fileoutputstream fos = new fileoutputstream("f:/2.png");
        imageio.write(bufferedimage, "png", fos);
        fos.flush();
        fos.close();
    }
}

Java用自带的Image IO给图片添加水印

3.  旋转坐标轴

import sun.font.fontdesignmetrics;
import javax.imageio.imageio;
import java.awt.*;
import java.awt.image.bufferedimage;
import java.io.file;
import java.io.fileoutputstream;
import java.io.ioexception;
/**
 * @author chengjiansheng
 * @date 2021/6/10
 */
public class watermarkutil
{
    // 水印透明度
    private static final float alpha = 0.5 f;
    // 水印文字字体
    private static final font font = new font("宋体", font.bold, 30);
    // 水印文字颜色
    private static final color color = color.red;
    public static void main(string[] args) throws ioexception
        {
            addtext("f:/1.jpeg", "图片由木叶村提供,仅供忍者联军使用!");
        }
        /**
         * 加文字水印
         * @param srcpath   原文件路径
         * @param content   文字内容
         * @throws ioexception
         */
    public static void addtext(string srcpath, string content) throws ioexception
    {
        //  读取原图片信息
        bufferedimage srcimage = imageio.read(new file(srcpath));
        int width = srcimage.getwidth();
        int height = srcimage.getheight();
        //  创建画笔,设置绘图区域
        bufferedimage bufferedimage = new bufferedimage(width, height, bufferedimage.type_int_rgb);
        graphics2d g = bufferedimage.creategraphics();
        g.drawimage(srcimage, 0, 0, width, height, null);
        g.setfont(font); // 字体
        g.setcolor(color); // 颜色
        g.setcomposite(alphacomposite.getinstance(alphacomposite.src_atop, alpha)); // 透明度
        //  计算文字宽高度
        fontdesignmetrics metrics = fontdesignmetrics.getmetrics(font);
        int textwidth = metrics.stringwidth(content); //  文字宽度
        int textheight = metrics.getheight(); //  文字高度
        //  旋转坐标轴
        g.translate(-width / 5, height / 4);
        g.rotate(-30 * math.pi / 180);
        //  计算文字坐标
        int x = (width - textwidth) / 2;
        int y = (height + textheight) / 2;
        //  写文字
        g.drawstring(content, x, y);
        //  画矩形
        int padding = 10; // 内边距
        g.drawrect(x - padding / 2, y - textheight, textwidth + padding, textheight + padding);
        g.dispose();
        //  输出文件
        fileoutputstream fos = new fileoutputstream("f:/2.png");
        imageio.write(bufferedimage, "png", fos);
        fos.flush();
        fos.close();
    }
}

Java用自带的Image IO给图片添加水印

结合下载功能,完整的代码如下:

/**
 * 下载
 */
@
getmapping("/download")
public void download(@requestparam("mediaid") string mediaid, httpservletrequest request, httpservletresponse response) throws ioexception
{
    sysfile sysfile = sysfileservice.getbymediaid(mediaid);
    if(null == sysfile)
    {
        throw new illegalargumentexception("文件不存在");
    }
    string mimetype = request.getservletcontext().getmimetype(sysfile.getpath());
    system.out.println(mimetype);
    response.setcontenttype(sysfile.getcontenttype());
    response.setheader(httpheaders.content_disposition, "attachment;filename=" + urlencoder.encode(sysfile.getoriginalfilename(), "utf-8"));
    //        fileinputstream fis = new fileinputstream(sysfile.getpath());
    servletoutputstream sos = response.getoutputstream();
    watermarkutil.addtext(sysfile.getpath(), "哈哈哈哈", sos);
    //        ioutils.copy(fis, sos);
    //        ioutils.closequietly(fis);
    ioutils.closequietly(sos);
}
import sun.font.fontdesignmetrics;
import javax.imageio.imageio;
import java.awt.*;
import java.awt.image.bufferedimage;
import java.io.file;
import java.io.ioexception;
import java.io.outputstream;
/**
 * @author chengjiansheng
 * @date 2021/6/10
 */
public class watermarkutil
{
    // 水印透明度
    private static final float alpha = 0.5 f;
    // 水印文字字体
    private static final font font = new font("宋体", font.bold, 30);
    // 水印文字颜色
    private static final color color = color.red;
    /**
     * 加文字水印
     * @param srcpath   原文件路径
     * @param content   文字内容
     * @throws ioexception
     */
    public static void addtext(string srcpath, string content, outputstream outputstream) throws ioexception
    {
        //  读取原图片信息
        bufferedimage srcimage = imageio.read(new file(srcpath));
        int width = srcimage.getwidth();
        int height = srcimage.getheight();
        //  画板
        bufferedimage bufferedimage = new bufferedimage(width, height, bufferedimage.type_int_rgb);
        //  画笔
        graphics2d g = bufferedimage.creategraphics();
        g.drawimage(srcimage, 0, 0, width, height, null);
        g.setfont(font); // 字体
        g.setcolor(color); // 颜色
        g.setcomposite(alphacomposite.getinstance(alphacomposite.src_atop, alpha)); // 透明度
        //  计算文字宽高度
        fontdesignmetrics metrics = fontdesignmetrics.getmetrics(font);
        int textwidth = metrics.stringwidth(content); //  文字宽度
        int textheight = metrics.getheight(); //  文字高度
        //  旋转坐标轴
        g.translate(-width / 5, height / 4);
        g.rotate(-30 * math.pi / 180);
        //  计算文字坐标
        int x = (width - textwidth) / 2;
        int y = (height + textheight) / 2;
        //  写文字
        g.drawstring(content, x, y);
        //  画矩形
        int padding = 10; // 内边距
        g.drawrect(x - padding / 2, y - textheight, textwidth + padding, textheight + padding);
        g.dispose();
        //  输出
        imageio.write(bufferedimage, "png", outputstream);
    }
}

另外的写法

import javax.imageio.imageio;
import java.awt.*;
import java.awt.image.bufferedimage;
import java.io.file;
import java.io.fileoutputstream;

/**
 * @projectname: test
 * @package: com.test.utils
 * @classname: mytest
 * @author: luqiming
 * @description:
 * @date: 2020/10/29 11:48
 * @version: 1.0
 */
public class addwatermarkutil {
    public static void waterpress(string srcimgpath, string outimgpath,
                           color markcontentcolor, int fontsize, string watermarkcontent) {
        try {
            string[] watermarkcontents = watermarkcontent.split("\\|\\|");
            // 读取原图片信息
            file srcimgfile = new file(srcimgpath);
            image srcimg = imageio.read(srcimgfile);
            int srcimgwidth = srcimg.getwidth(null);
            int srcimgheight = srcimg.getheight(null);
            // 加水印
            bufferedimage bufimg = new bufferedimage(srcimgwidth, srcimgheight, bufferedimage.type_int_rgb);
            // 得到画笔对象
            graphics2d g = bufimg.creategraphics();
            // 设置起点
            g.drawimage(srcimg, 0, 0, srcimgwidth, srcimgheight, null);
            font font = new font("宋体", font.plain, fontsize);
            // 根据图片的背景设置水印颜色
            g.setcolor(markcontentcolor);
            // 设置水印文字字体
            g.setfont(font);
            // 数组长度
            int contentlength = watermarkcontents.length;
            // 获取水印文字中最长的
            int maxlength = 0;
            for (int i = 0; i < contentlength; i++) {
                int fontlen = getwatermarklength(watermarkcontents[i], g);
                if (maxlength < fontlen) {
                    maxlength = fontlen;
                }
            }

            for (int j = 0; j < contentlength; j++) {
                watermarkcontent = watermarkcontents[j];
                int tempx = 10;
                int tempy = fontsize;
                // 单字符长度
                int tempcharlen = 0;
                // 单行字符总长度临时计算
                int templinelen = 0;
                stringbuffer sb = new stringbuffer();
                for (int i = 0; i < watermarkcontent.length(); i++) {
                    char tempchar = watermarkcontent.charat(i);
                    tempcharlen = getcharlen(tempchar, g);
                    templinelen += tempcharlen;
                    if (templinelen >= srcimgwidth) {
                        // 长度已经满一行,进行文字叠加
                        g.drawstring(sb.tostring(), tempx, tempy);
                        // 清空内容,重新追加
                        sb.delete(0, sb.length());
                        templinelen = 0;
                    }
                    // 追加字符
                    sb.append(tempchar);
                }
                // 通过设置后两个输入参数给水印定位
                g.drawstring(sb.tostring(), 20, srcimgheight - (contentlength - j - 1) * tempy-50);
            }
            g.dispose();

            // 输出图片
            fileoutputstream outimgstream = new fileoutputstream(outimgpath);
            imageio.write(bufimg, "jpg", outimgstream);
            outimgstream.flush();
            outimgstream.close();
        } catch (exception e) {
            e.printstacktrace();
        }
    }

    public static int getcharlen(char c, graphics2d g) {
        return g.getfontmetrics(g.getfont()).charwidth(c);
    }

    /**
     * 获取水印文字总长度
     *
     * @paramwatermarkcontent水印的文字
     * @paramg
     * @return水印文字总长度
     */
    public static int getwatermarklength(string watermarkcontent, graphics2d g) {
        return g.getfontmetrics(g.getfont()).charswidth(
                watermarkcontent.tochararray(), 0, watermarkcontent.length());
    }


    public static void main(string[] args) {
        // 原图位置, 输出图片位置, 水印文字颜色, 水印文字
        string font = "张天爱||就很完美||2020-05-27 17:00:00";
        string inputaddress = "f:/upupoowallpaper/1.jpg";
        string outputaddress = "f:/upupoowallpaper/1.jpg";
        color color = color.green;
        waterpress(inputaddress, outputaddress, color, 50, font);
    }
}

添加效果

Java用自带的Image IO给图片添加水印

关于水印位置,需要修改:

//左下角
 g.drawstring(sb.tostring(), 0, srcimgheight - (contentlength - j - 1) * tempy);

//右下角
 g.drawstring(sb.tostring(), srcimgwidth - maxlength, srcimgheight - (contentlength - j - 1) * tempy);

以上就是java用自带的image io给图片添加水印的详细内容,更多关于java 图片添加水印的资料请关注其它相关文章!