Java实现图片添加单个文字水印、多个文字水印、图片水印、马赛克

给图片添加文字水印

设置文字的位置、大小、样式、类型、透明度、颜色等

给图片添单个文字水印

/*
* 给图片添加单个文字水印类
* */
public class TextWatermarking {

    //定义图片水印字体类型
    public static final String FONT_NAME = "微软雅黑";


    //定义图片水印字体加粗、变细、倾斜等样式
    public static final int FONT_STYLE = Font.BOLD;

    //设置字体大小
    public static final int FONT_SIZE = 120;

    //设置文字透明程度
    public static float ALPHA = 0.3F;

    /**
     * 给图片添加单个文字水印、可设置水印文字旋转角度
     * source 需要添加水印的图片路径(如:F:/images/6.jpg)
     * outPut 添加水印后图片输出路径(如:F:/images/)
     * imageName 图片名称
     * imageType 图片类型
     * color 水印文字的颜色
     * word 水印文字
     * degree 水印文字旋转角度,为null表示不旋转
     */

    public Boolean markImageBySingleText(String sourcePath, String outputPath, String imageName, String imageType, Color color, String word, Integer degree) {

        try {

            //读取原图片信息
            File file = new File(sourcePath);

            if (!file.isFile()) {
                return false;
            }

            //获取源图像的宽度、高度
            Image image = ImageIO.read(file);
            int width = image.getWidth(null);
            int height = image.getHeight(null);

            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

            //创建绘图工具对象
            Graphics2D graphics2D = bufferedImage.createGraphics();
            //其中的0代表和原图位置一样
            graphics2D.drawImage(image, 0, 0, width, height, null);

            //设置水印文字(设置水印字体样式、粗细、大小)
            graphics2D.setFont(new Font(FONT_NAME, FONT_STYLE, FONT_SIZE));

            //设置水印颜色
            graphics2D.setColor(color);

            //设置水印透明度
            graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,ALPHA));

            //设置水印旋转
            if (null != degree) {
                graphics2D.rotate(Math.toRadians(degree),(double) bufferedImage.getWidth() / 2, (double) bufferedImage.getHeight() / 2);
            }

            int x = width - (FONT_SIZE * 4);
            int y = height/2;

            //进行绘制
            graphics2D.drawString(word, x, y);
            graphics2D.dispose();

            //输出图片
            File sf = new File(outputPath, imageName+"."+imageType);
            // 保存图片
            ImageIO.write(bufferedImage, imageType, sf);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
}

给图片添加多个文字水印 

/*
* 给图片添加多个文字水印类
* */
public class TextWatermarking {

    //定义图片水印字体类型
    public static final String FONT_NAME = "微软雅黑";


    //定义图片水印字体加粗、变细、倾斜等样式
    public static final int FONT_STYLE = Font.BOLD;

    //设置字体大小
    public static final int FONT_SIZE = 120;

    //设置文字透明程度
    public static float ALPHA = 0.3F;

    /**
     * 给图片添加多个文字水印、可设置水印文字旋转角度
     * source 需要添加水印的图片路径
     * outPut 添加水印后图片输出路径
     * imageName 图片名称
     * imageType 图片类型
     * color 水印文字的颜色
     * word 水印文字
     * degree 水印文字旋转角度,为null表示不旋转
     */
    public Boolean markImageByMoreText(String sourcePath, String outputPath, String imageName, String imageType, Color color, String word, Integer degree) {
        try {
            //读取原图片信息
            File file = new File(sourcePath);

            if (!file.isFile()) {
                return false;
            }

            //获取源图像的宽度、高度
            Image image = ImageIO.read(file);
            int width = image.getWidth(null);
            int height = image.getHeight(null);

            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

            //创建绘图工具对象
            Graphics2D graphics2D = bufferedImage.createGraphics();
            //其中的0代表和原图位置一样
            graphics2D.drawImage(image, 0, 0, width, height, null);

            //设置水印文字(设置水印字体样式、粗细、大小)
            graphics2D.setFont(new Font(FONT_NAME, FONT_STYLE, FONT_SIZE));

            //设置水印颜色
            graphics2D.setColor(color);

            //设置水印透明度
            graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));

            //设置水印旋转
            if (null != degree) {
                graphics2D.rotate(Math.toRadians(degree), (double) bufferedImage.getWidth() / 2, (double) bufferedImage.getHeight() / 2);
            }

            int x = width / 3;
            int y = FONT_SIZE;
            int space = height / FONT_SIZE;
            for (int i = 0; i < space; i++) {
                //如果最后一个坐标的y轴比height高,直接退出
                if ((y + FONT_SIZE) > height) {
                    break;
                }
                //进行绘制
                graphics2D.drawString(word, x, y);
                y += (2 * FONT_SIZE);
            }

            graphics2D.dispose();

            //输出图片
            File sf = new File(outputPath, imageName + "." + imageType);
            // 保存图片
            ImageIO.write(bufferedImage, imageType, sf);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
}

给图片添加图片水印

设置图片水印的位置、旋转角度等

给图片添单个图片水印

/*
* 给图片添加单个图片水印、可设置水印图片旋转角度
* */
public class ImageWatermark {

    /**
     *icon 水印图片路径(如:F:/images/icon.png)
     *source 没有加水印的图片路径(如:F:/images/6.jpg)
     *output 加水印后的图片路径(如:F:/images/)
     *imageName 图片名称(如:11111)
     *imageType 图片类型(如:jpg)
     *degree 水印图片旋转角度,为null表示不旋转
     */
    public Boolean markImageBySingleIcon(String icon,String source,String output,String imageName,String imageType,Integer degree) {

        try {
            File file = new File(source);
            File ficon = new File(icon);

            if (!file.isFile()) {
                return false;
            }

            //将icon加载到内存中
            Image ic = ImageIO.read(ficon);
            //icon高度
            int icheight = ic.getHeight(null);
            //将源图片读到内存中
            Image img = ImageIO.read(file);

            //图片宽
            int width = img.getWidth(null);
            //图片高
            int height = img.getHeight(null);

            BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
            //创建一个指定 BufferedImage 的 Graphics2D 对象
            Graphics2D g = bi.createGraphics();

            //x,y轴默认是从0坐标开始
            int x = 0;
            int y = (height/2)-(icheight/2);

            //设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            //呈现一个图像,在绘制前进行从图像空间到用户空间的转换
            g.drawImage(img.getScaledInstance(width,height,Image.SCALE_SMOOTH),0,0,null);

            if (null != degree) {
                //设置水印旋转
                g.rotate(Math.toRadians(degree),(double) bi.getWidth() / 2, (double) bi.getHeight() / 2);
            }
            //水印图象的路径 水印一般为gif或者png的,这样可设置透明度
            ImageIcon imgIcon = new ImageIcon(icon);
            //得到Image对象。
            Image con = imgIcon.getImage();
            //透明度,最小值为0,最大值为1
            float clarity = 0.6f;
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,clarity));
            //表示水印图片的坐标位置(x,y)
            //g.drawImage(con, 300, 220, null);
            g.drawImage(con, x, y, null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
            g.dispose();
            File sf = new File(output, imageName+"."+imageType);
            ImageIO.write(bi, imageType, sf); // 保存图片

        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
}

给图片添加多个图片水印

/*
* 给图片不同位置添加多个图片水印、可设置水印图片旋转角度
* */
public class ImageWatermark {

    /**
     * icon 水印图片路径
     * source 没有加水印的图片路径
     * output 加水印后的图片路径
     * imageName 图片名称
     * imageType 图片类型
     * degree 水印图片旋转角度,为null表示不旋转
     */
    public Boolean markImageByMoreIcon(String icon,String source,String output,String imageName,String imageType,Integer degree) {

        try {
            File file = new File(source);
            
            File ficon = new File(icon);
            
            if (!file.isFile()) {
                return false;
            }
            //将icon加载到内存中
            Image ic = ImageIO.read(ficon);
            
            //icon高度
            int icheight = ic.getHeight(null);
            
            //将源图片读到内存中
            Image img = ImageIO.read(file);
            
            //图片宽
            int width = img.getWidth(null);
            //图片高
            int height = img.getHeight(null);
            
            BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
            //创建一个指定 BufferedImage 的 Graphics2D 对象
            Graphics2D g = bi.createGraphics();
            
            //x,y轴默认是从0坐标开始
            int x = 0;
            int y = 0;
            
            //默认两张水印图片的间隔高度是水印图片的1/3
            int temp = icheight/3;
            int space = 1;
            if(height>=icheight){
                space = height/icheight;
                if(space>=2){
                    temp = y = icheight/2;
                    if(space==1||space==0){
                        x = 0;
                        y = 0;
                    }
                }
            }else{
                x = 0;
                y = 0;
            }
            
            //设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            
            //呈现一个图像,在绘制前进行从图像空间到用户空间的转换
            g.drawImage(img.getScaledInstance(width,height,Image.SCALE_SMOOTH),0,0,null);
            for(int i=0;i<space;i++){
                if (null != degree) {
                    //设置水印旋转
                    g.rotate(Math.toRadians(degree),(double) bi.getWidth() / 2, (double) bi.getHeight() / 2);
                }
                //水印图象的路径 水印一般为gif或者png的,这样可设置透明度
                ImageIcon imgIcon = new ImageIcon(icon);
                //得到Image对象。
                Image con = imgIcon.getImage();
                //透明度,最小值为0,最大值为1
                float clarity = 0.6f;
                g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,clarity));
                //表示水印图片的坐标位置(x,y)
                //g.drawImage(con, 300, 220, null);
                g.drawImage(con, x, y, null);
                g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
                y+=(icheight+temp);
            }
            g.dispose();
            File sf = new File(output, imageName+"."+imageType);
            ImageIO.write(bi, imageType, sf); // 保存图片
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
}

给图片添加马赛克

设置马赛克的尺寸、每个马赛克的宽和高

/*
* 给图片添加马赛克
* */
public class MosaicImage {

    /**
     * source 原图片路径
     * output 打马赛克后,图片保存的路径
     * imageName 图片名称
     * imageType 图片类型
     * size 马赛克尺寸,即每个矩形的宽高
     */
    public Boolean markImageByMosaic(String source,String output,String imageName,String imageType,int size){

        try{
            File file = new File(source);
            if (!file.isFile()) {
                return false;
            }
            BufferedImage img = ImageIO.read(file); // 读取该图片
            int width = img.getWidth(null); //原图片宽
            int height = img.getHeight(null); //原图片高
            BufferedImage bi = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
            //马赛克格尺寸太大或太小
            if (width < size || height < size) {
                return false;
            }
            if(size<=0){
                return false;
            }
            int xcount = 0; //x方向绘制个数
            int ycount = 0; //y方向绘制个数

            if (width % size == 0) {
                xcount = width / size;
            } else {
                xcount = width / size + 1;
            }

            if (height % size == 0) {
                ycount = height / size;
            } else {
                ycount = height / size + 1;
            }

            int x = 0; //x坐标
            int y = 0;//y坐标

            //绘制马赛克(绘制矩形并填充颜色)
            Graphics2D g = bi.createGraphics();
            for (int i = 0; i < xcount; i++) {
                for (int j = 0; j < ycount; j++) {
                    //马赛克矩形格大小
                    int mwidth = size;
                    int mheight = size;
                    if(i==xcount-1){  //横向最后一个不够一个size
                        mwidth = width-x;
                    }

                    if(j == ycount-1){ //纵向最后一个不够一个size
                        mheight = height-y;
                    }

                    //矩形颜色取中心像素点RGB值
                    int centerX = x;
                    int centerY = y;

                    if (mwidth % 2 == 0) {
                        centerX += mwidth / 2;
                    } else {
                        centerX += (mwidth - 1) / 2;
                    }

                    if (mheight % 2 == 0) {
                        centerY += mheight / 2;
                    } else {
                        centerY += (mheight - 1) / 2;
                    }

                    Color color = new Color(img.getRGB(centerX, centerY));
                    g.setColor(color);
                    g.fillRect(x, y, mwidth, mheight);
                    y = y + size;// 计算下一个矩形的y坐标
                }

                y = 0;// 还原y坐标
                x = x + size;// 计算x坐标
            }
            g.dispose();
            File sf = new File(output, imageName+"."+imageType);
            ImageIO.write(bi, imageType, sf); // 保存图片

        }catch(Exception e){
            e.printStackTrace();
        }
        return true;
    }
}

 

  • 5
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 在 Java 后台程序中,你可以使用 HTTP POST 请求来接收多个图片文件和文字信息。 具体来说,你需要使用一个表单来包含你的文字信息和文件输入字段,然后使用 Java 的 Servlet 或者 Spring MVC 框架来处理 HTTP POST 请求。 例如,你可以使用如下的 HTML 表单来提交文字信息和文件: ```html <form action="/upload" method="post" enctype="multipart/form-data"> <input type="text" name="textField" value="some text"> <input type="file" name="fileField1" multiple> <input type="file" name="fileField2" multiple> <button type="submit">Submit</button> </form> ``` 然后,在 Java 后台程序中,你可以使用如下的代码来处理这个 HTTP POST 请求: ```java @PostMapping("/upload") public void handleFileUpload(@RequestParam("textField") String text, @RequestParam("fileField1") MultipartFile file1, @RequestParam("fileField2") MultipartFile file2) { // 获取文字信息 String textField = text; // 获取文件内容 byte[] file1Content = file1.getBytes(); byte[] file2Content = file2.getBytes(); // 处理文字信息和文件内容 ... } ``` 在上面的代码中,`@PostMapping("/upload")` 注解用来处理 HTTP POST 请求,`@RequestParam` 注解用来获取表单中的文字信息和文件内容。 注意:为了使用 `MultipartFile` 类来处理文件内容,你需要在你的后台程序中添加对 `commons-fileupload` 和 `commons-io` 包的依赖。 ### 回答2: 在Java后台接收多个图片文件和文字信息可以使用Multipart/form-data格式进行传输。 首先,客户端需要使用表单提交方式将图片文件和文字信息一起发送到Java后台。表单的enctype属性需要设置为"multipart/form-data",这样可以保证图片文件能够正确地通过HTTP协议传输。 然后,在Java后台,可以使用一些常用的框架如SpringMVC或Servlet来处理接收到的请求。这些框架都提供了对Multipart/form-data格式进行解析的功能。 在SpringMVC中,可以使用@RequestParam注解来接收单个文件,并使用@RequestPart注解来接收多个文件。示例代码如下: ```java @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file, @RequestPart("files") MultipartFile[] files, @RequestParam("text") String text) { // 处理接收到的文件和文字信息 // ... return "success"; } ``` 在Servlet中,可以通过HttpServletRequest的getPart方法来获取上传的文件对象,通过getParameter方法来获取文字信息。示例代码如下: ```java protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取文件上传的对象 Part filePart = request.getPart("file"); Collection<Part> fileParts = request.getParts("files"); // 获取文字信息 String text = request.getParameter("text"); // 处理接收到的文件和文字信息 // ... } ``` 在处理接收到的文件和文字信息时,可以根据实际需求进行操作,例如将文件保存到磁盘上的指定位置,或者将文字信息存储到数据库中等。相关的操作可以使用Java IO或者持久化框架来完成。 总之,通过使用Multipart/form-data格式,Java后台可以接收并处理多个图片文件和文字信息。 ### 回答3: 在Java后端,可以使用MultipartHttpServletRequest来接收多个图片文件和文字信息。 首先,前端可以使用HTML的<form>标签并设置enctype为"multipart/form-data"来实现文件上传。然后在Java后端,可以使用HttpServletRequest来接收请求,然后将其转换为MultipartHttpServletRequest对象。 接下来,可以通过MultipartHttpServletRequest对象的getFiles()方法来获取所有上传的文件。可以使用该方法返回的MultipartFile数组来逐个操作每个文件。可以使用MultipartFile对象的getOriginalFilename()方法获取文件名,使用getContentType()方法获取文件类型,使用getBytes()方法获取文件内容的字节数组等。 此外,还可以通过MultipartHttpServletRequest对象的getParameter()方法来获取表单中的其他文本参数。可以通过该方法传递参数名来获取对应的值。 总结起来,可以使用MultipartHttpServletRequest对象获取多个图片文件和文字信息。对于文件,可以使用MultipartFile对象获取文件名、类型和内容。对于文字信息,可以使用MultipartHttpServletRequest对象的getParameter()方法获取表单中的其他参数值。 注意:在使用MultipartHttpServletRequest接收文件时,需要在后端的配置文件中设置合适的文件上传配置,如设置文件保存路径、最大文件大小等。另外,还需要相关的依赖库来支持文件上传功能,如Apache Commons FileUpload或Spring的MultipartResolver等。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值