java图片添加水印实现自动换行

package com.tgpms.utils;

import cn.hutool.core.util.StrUtil;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;

/**
 * 图片添加水印
 *
 * @author jiangli
 * @since 2021/3/11 8:23
 */
public class WaterMarkUtil {

    // 用来调整水印的间距
    private static final int space = 20;

    /**
     * 
     * @param srcImgFile 待添加水印的图片
     * @param outImgPath 添加完成的输出路径
     * @param markContentColor 文字颜色
     * @param waterMarkContent 水印内容, 需要换行用||连接
     */
    public static void drawCaterMark(File srcImgFile, String outImgPath, Color markContentColor, 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);
            int fontSize = srcImg.getWidth(null) / 300 * 10;
            Font font = new Font("微软雅黑", Font.PLAIN, fontSize);
            // 设置水印颜色
            g.setColor(markContentColor);
            // 设置水印文字字体
            g.setFont(font);
            // 抗锯齿
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);

            java.util.List<String> waterMarkContentList = new ArrayList<>();
            // 将换行后的文字放入新的集合
            for (String markContent : waterMarkContents) {
                // 单字符长度
                int tempCharLen = 0;
                // 单行字符总长度临时计算
                int tempLineLen = 0;
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < markContent.length(); i++) {
                    char tempChar = markContent.charAt(i);
                    tempCharLen = getCharLen(tempChar, g);
                    tempLineLen += tempCharLen;
                    // 文字长度大于图片宽度-2*间距-字体大小
                    if (tempLineLen > srcImgWidth - space * 2 - tempCharLen) {
                        // 长度已经满一行
                        waterMarkContentList.add(sb.toString());
                        // 清空内容,重新追加
                        sb.delete(0, sb.length());
                        tempLineLen = 0;
                    }
                    // 追加字符
                    sb.append(tempChar);
                }
                waterMarkContentList.add(sb.toString());
            }

            // 绘制水印
            int tempY = fontSize + space;
            for (int i = 0; i < waterMarkContentList.size(); i++) {
                String s = waterMarkContentList.get(i);
                //左上角
//                g.drawString(s, space, i * tempY + 2 * space);
                //右下角
                g.drawString(s, space, srcImgHeight - (waterMarkContentList.size() - i) * tempY + space);
            }
            g.dispose();

            // 输出图片
            if (StrUtil.isNotBlank(outImgPath)) {
                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);
    }

    /**
     * 获取水印文字总长度
     *
     * @param waterMarkContent 水印的文字
     * @param g                绘图方法
     * @return 水印文字总长度
     */
    public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }
}

使用

    /**
     * 新增新建管网信息管道
     */
    @ApiOperation(value = "新增新建管网信息管道", notes = "新增新建管网信息管道", httpMethod = "POST")
    @PostMapping(value = "/tofly-sxgk/newpspipe", headers = "content-type=multipart/form-data")
    public Result addNewpspipe(@RequestParam(value = "newpspipe") String jsonString,@RequestParam String waterMarkContent, HttpServletRequest request) {
        InLineParts inLineParts = JSONUtil.toBean(jsonString, InLineParts.class);
        List<MultipartFile> files = new ArrayList<>();
        // 获取文件集合
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        if (CollectionUtil.isNotEmpty(fileMap)) {
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 获取单个文件
                MultipartFile mf = entity.getValue();
                files.add(mf);
            }
        }

        // 临时文件,最后要删除
        List<File> images = new ArrayList<>();
        try {
            // 发送给同飞的参数
            Map<String, Object> paramMap = new HashMap<>();
            if (CollectionUtil.isNotEmpty(inLineParts.getNewpspipefileList())) {
                List<Newpspipefile> newpspipefileList = inLineParts.getNewpspipefileList();
                for (int i = 0; i < newpspipefileList.size(); i++) {
                    Newpspipefile newpspipefile = newpspipefileList.get(i);
                    paramMap.put("newpspipefileList[" + i + "].fileName", newpspipefile.getFileName());
                    paramMap.put("newpspipefileList[" + i + "].distance", newpspipefile.getDistance());
                    paramMap.put("newpspipefileList[" + i + "].latitude", newpspipefile.getLatitude());
                    paramMap.put("newpspipefileList[" + i + "].longitude", newpspipefile.getLongitude());
                    paramMap.put("newpspipefileList[" + i + "].sxCoor", newpspipefile.getSxCoor());
                    paramMap.put("newpspipefileList[" + i + "].syCoor", newpspipefile.getSyCoor());
                    File image = MultipartFileToFile.multipartFileToFile(files.get(i));
                    // 添加水印(MultipartFile要转换成File,生成的带水印的图片替换掉原来的临时图片,临时图片最后删除)
                    CaterMarkUtil.drawCaterMark(image,image.getPath(), Color.red,waterMarkContent);
                    paramMap.put(newpspipefile.getFileName(), image);
                    images.add(image);
                }
            }

            // 调用同飞修改接口
            paramMap.putAll(BeanUtil.beanToMap(inLineParts, false, true));
            paramMap.remove("newpspipefileList");
            String token = request.getHeader("tfToken");
            String body = HttpRequest.post(PropertiesUtil.HOST + tongFeiUrl.getNewpspipe())
                    .header(Header.AUTHORIZATION, "Bearer " + token)
                    .header(Header.CONTENT_TYPE, "multipart/form-data")
                    .form(paramMap)
                    .execute().body();
            R r = JSON.parseObject(body, R.class);
            return CommonMethods.tongFeiResponseToResult(r);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        } finally {
            MultipartFileToFile.delteTempFile(images);
        }
    }

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
您好!针对您的问题,您可以通过以下步骤来实现在 Android 图片的左下角添加多行水印自动换行: 1. 创建一个 Bitmap 对象,将其设置为原始图片的副本。 2. 创建一个 Canvas 对象,将其设置为 Bitmap 对象。 3. 创建一个 TextPaint 对象,设置水印的文字大小、颜色、字体等属性。 4. 使用 StaticLayout 类来绘制多行文本,并将其添加到 Canvas 对象的左下角。 5. 将新的 Bitmap 对象保存到设备上。 下面是一个示例代码片段,演示如何在 Android 图片的左下角添加多行水印自动换行: ``` Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.original_image); Bitmap bitmapCopy = originalBitmap.copy(Bitmap.Config.ARGB_8888, true); Canvas canvas = new Canvas(bitmapCopy); TextPaint textPaint = new TextPaint(); textPaint.setTextSize(20); textPaint.setColor(Color.WHITE); textPaint.setAntiAlias(true); String watermarkText = "This is a multi-line watermark text.\nIt will be automatically wrapped."; StaticLayout textLayout = new StaticLayout(watermarkText, textPaint, canvas.getWidth(), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); canvas.save(); canvas.translate(0, canvas.getHeight() - textLayout.getHeight()); textLayout.draw(canvas); canvas.restore(); FileOutputStream outStream = new FileOutputStream("/sdcard/watermarked_image.jpg"); bitmapCopy.compress(Bitmap.CompressFormat.JPEG, 100, outStream); outStream.flush(); outStream.close(); ``` 请注意,上述代码仅供参考,您需要根据实际情况进行适当调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值