电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術(shù)文章
文章詳情頁

Java用自帶的Image IO給圖片添加水印

瀏覽:95日期:2022-08-10 14:39:35
目錄1. 文字水印2. 旋轉(zhuǎn)文字3. 旋轉(zhuǎn)坐標(biāo)軸另外的寫法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 文字內(nèi)容 * @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();// 創(chuàng)建畫筆,設(shè)置繪圖區(qū)域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);// 計算文字坐標(biāo)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給圖片添加水印

可以設(shè)置文字透明度

g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.8f)); 2. 旋轉(zhuǎn)文字

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', '圖片由木葉村提供,僅供忍者聯(lián)軍使用!');}/** * 加文字水印 * @param srcPath 原文件路徑 * @param content 文字內(nèi)容 * @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();// 創(chuàng)建畫筆,設(shè)置繪圖區(qū)域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);// 旋轉(zhuǎn)文字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);// 計算水印文字坐標(biāo)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', '圖片由木葉村提供,僅供忍者聯(lián)軍使用!');}/** * 加文字水印 * @param srcPath 原文件路徑 * @param content 文字內(nèi)容 * @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();// 創(chuàng)建畫筆,設(shè)置繪圖區(qū)域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(); // 文字高度// 計算文字坐標(biāo)int x = (width - textWidth) / 2;int y = (height + textHeight) / 2;// 寫文字g.drawString(content, x, y);// 畫矩形int padding = 10; // 內(nèi)邊距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. 旋轉(zhuǎn)坐標(biāo)軸

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', '圖片由木葉村提供,僅供忍者聯(lián)軍使用!');}/** * 加文字水印 * @param srcPath 原文件路徑 * @param content 文字內(nèi)容 * @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();// 創(chuàng)建畫筆,設(shè)置繪圖區(qū)域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(); // 文字高度// 旋轉(zhuǎn)坐標(biāo)軸g.translate(-width / 5, height / 4);g.rotate(-30 * Math.PI / 180);// 計算文字坐標(biāo)int x = (width - textWidth) / 2;int y = (height + textHeight) / 2;// 寫文字g.drawString(content, x, y);// 畫矩形int padding = 10; // 內(nèi)邊距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給圖片添加水印

結(jié)合下載功能,完整的代碼如下:

/** * 下載 */@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 文字內(nèi)容 * @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(); // 文字高度// 旋轉(zhuǎn)坐標(biāo)軸g.translate(-width / 5, height / 4);g.rotate(-30 * Math.PI / 180);// 計算文字坐標(biāo)int x = (width - textWidth) / 2;int y = (height + textHeight) / 2;// 寫文字g.drawString(content, x, y);// 畫矩形int padding = 10; // 內(nèi)邊距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(); // 設(shè)置起點 g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null); Font font = new Font('宋體', Font.PLAIN, fontSize); // 根據(jù)圖片的背景設(shè)置水印顏色 g.setColor(markContentColor); // 設(shè)置水印文字字體 g.setFont(font); // 數(shù)組長度 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) {// 長度已經(jīng)滿一行,進(jìn)行文字疊加g.drawString(sb.toString(), tempX, tempY);// 清空內(nèi)容,重新追加sb.delete(0, sb.length());tempLineLen = 0; } // 追加字符 sb.append(tempChar);}// 通過設(shè)置后兩個輸入?yún)?shù)給水印定位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 = '張?zhí)鞇踻|就很完美||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給圖片添加水印

關(guān)于水印位置,需要修改:

//左下角 g.drawString(sb.toString(), 0, srcImgHeight - (contentLength - j - 1) * tempY);//右下角 g.drawString(sb.toString(), srcImgWidth - maxLength, srcImgHeight - (contentLength - j - 1) * tempY);

以上就是Java用自帶的Image IO給圖片添加水印的詳細(xì)內(nèi)容,更多關(guān)于Java 圖片添加水印的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: Java
相關(guān)文章:
主站蜘蛛池模板: 防爆型气象站_农业气象站_校园气象站_农业四情监测系统「山东万象环境科技有限公司」 | 电动垃圾车,垃圾清运车-江苏速利达机车有限公司 | 合肥汽车充电桩_安徽充电桩_电动交流充电桩厂家_安徽科帝新能源科技有限公司 | 游戏版号转让_游戏资质出售_游戏公司转让-【八九买卖网】 | 全自动翻转振荡器-浸出式水平振荡器厂家-土壤干燥箱价格-常州普天仪器 | 香港新时代国际美容美发化妆美甲培训学校-26年培训经验,值得信赖! | 亚克隆,RNAi干扰检测,miRNA定量检测-上海基屹生物科技有限公司 | 制丸机,小型中药制丸机,全自动制丸机价格-甘肃恒跃制药设备有限公司 | 在线浊度仪_悬浮物污泥浓度计_超声波泥位计_污泥界面仪_泥水界面仪-无锡蓝拓仪表科技有限公司 | 皮带机_移动皮带机_大倾角皮带机_皮带机厂家 - 新乡市国盛机械设备有限公司 | 北京中航时代-耐电压击穿试验仪厂家-电压击穿试验机 | 搪瓷搅拌器,搪玻璃搅拌器,搪玻璃冷凝器_厂家-淄博越宏化工设备 | 圆周直径尺-小孔内视镜-纤维研磨刷-东莞市高腾达精密工具 | 心肺复苏模拟人|医学模型|急救护理模型|医学教学模型上海康人医学仪器设备有限公司 | 鼓风干燥箱_真空烘箱_高温干燥箱_恒温培养箱-上海笃特科学仪器 | 喷涂流水线,涂装流水线,喷漆流水线-山东天意设备科技有限公司 | 304不锈钢无缝管_不锈钢管厂家 - 隆达钢业集团有限公司 | 飞象网 - 通信人每天必上的网站 全球化工设备网—化工设备,化工机械,制药设备,环保设备的专业网络市场。 | KBX-220倾斜开关|KBW-220P/L跑偏开关|拉绳开关|DHJY-I隔爆打滑开关|溜槽堵塞开关|欠速开关|声光报警器-山东卓信有限公司 | 永嘉县奥阳陶瓷阀门有限公司| 电梯乘运质量测试仪_电梯安全评估测试仪-武汉懿之刻 | 德州网站制作 - 网站建设设计 - seo排名优化 -「两山建站」 | 昆山新莱洁净应用材料股份有限公司-卫生级蝶阀,无菌取样阀,不锈钢隔膜阀,换向阀,离心泵 | 塑木弯曲试验机_铜带拉伸强度试验机_拉压力测试台-倾技百科 | 上海道勤塑化有限公司 | 黄石妇科医院_黄石东方女子医院_黄石东方妇产医院怎么样 | 昆明网络公司|云南网络公司|昆明网站建设公司|昆明网页设计|云南网站制作|新媒体运营公司|APP开发|小程序研发|尽在昆明奥远科技有限公司 | Jaeaiot捷易科技-英伟达AI显卡模组/GPU整机服务器供应商 | 高铝砖-高铝耐火球-高铝耐火砖生产厂家-价格【荣盛耐材】 | 安平县鑫川金属丝网制品有限公司,防风抑尘网,单峰防风抑尘,不锈钢防风抑尘网,铝板防风抑尘网,镀铝锌防风抑尘网 | 智慧食堂_食堂管理系统_食堂订餐_食堂消费系统—客易捷 | 小小作文网_中小学优秀作文范文大全 | PC构件-PC预制构件-构件设计-建筑预制构件-PC构件厂-锦萧新材料科技(浙江)股份有限公司 | 潍坊青州古城旅游景点攻略_青州酒店美食推荐-青州旅游网 | 清管器,管道清管器,聚氨酯发泡球,清管球 - 承德嘉拓设备 | 济南玻璃安装_济南玻璃门_济南感应门_济南玻璃隔断_济南玻璃门维修_济南镜片安装_济南肯德基门_济南高隔间-济南凯轩鹏宇玻璃有限公司 | Copeland/谷轮压缩机,谷轮半封闭压缩机,谷轮涡旋压缩机,型号规格,技术参数,尺寸图片,价格经销商 CTP磁天平|小电容测量仪|阴阳极极化_双液系沸点测定仪|dsj电渗实验装置-南京桑力电子设备厂 | 天然气分析仪-液化气二甲醚分析仪|传昊仪器| 网站seo优化_seo云优化_搜索引擎seo_启新网络服务中心 | 万博士范文网-您身边的范文参考网站Vanbs.com | 昊宇水工|河北昊宇水工机械工程有限公司|