图片加水印(java版)
JAVA不使用POI给Word文档添加水印[PageOffice]
JAVA不使用POI给Word文档添加水印[PageOffice]程序员在开发项目时,经常需要给一些图片、文件添加水印,但往往代码编写复杂,只能是先将文件上传再调用Graphics类才能实现这一功能。
但是最无奈的是这个类只能给图片添加水印,而无法通过程序给Word文件添加水印,那如何实现这一功能呢,下面我就来和大家分享一下一种简单的实现方法吧。
第一步:拷贝文件到WEB项目的“WEB-INF/lib”目录下。
拷贝PageOffice 示例中下的“WEB-INF/lib”路径中的pageoffice.cab和pageoffice.jar到新建项目的“WEB-INF/lib”目录下。
第二步:修改WEB项目的配置文件。
将如下代码添加到配置文件中:<!-- PageOffice Begin --><servlet><servlet-name>poserver</servlet-name><servlet-class>com.zhuozhengsoft .pageoffice.poserver.Server</servlet-class></servlet><servlet-mapping><servlet-name>poserver</servlet-name><url-pattern>/poserver.do</url-pattern></servlet-mapping><servlet-mapping><servlet-name>poserver</servlet-name><url-pattern>/pageoffice.cab</url-pattern></servlet-mapping><servlet-mapping><servlet-name>poserver</servlet-name><url-pattern>/popdf.cab</url-pattern></servlet-mapping><servlet-mapping><servlet-name>poserver</servlet-name><url-pattern>/sealsetup.exe</url-pattern></servlet-mapping><servlet><servlet-name>adminseal</servlet-name><servlet-class>com.zhuozhengsoft.pageoffice.poserver.AdminSeal </servlet-class></servlet><servlet-mapping><servlet-name>adminseal</servlet-name><url-pattern>/adminseal.do</url-pattern></servlet-mapping><servlet-mapping><servlet-name>adminseal</servlet-name><url-pattern>/loginseal.do</url-pattern></servlet-mapping><servlet-mapping><servlet-name>adminseal</servlet-name><url-pattern>/sealimage.do</url-pattern></servlet-mapping><mime-mapping><extension>mht</extension><mime-type>message/rfc822</mime-type></mime-mapping><context-param><param-name>adminseal-password</param-name><param-value>123456</param-value></context-param><!-- PageOffice End -->第三步:添加引用。
java实现图片加水印效果
java实现图⽚加⽔印效果图⽚加⽔印代码,这些代码不常⽤,但是⽤到的时候需要注意的地⽅也挺多的,每次都重写⽐较⿇烦,记下来备忘。
代码是图⽚加⽔印的⼀般流程,可根据实际项⽬需要⾃⾏修改。
注:代码在JPG和PNG格式图⽚下测试通过,其他图⽚格式请⾃⾏测试和修改import java.awt.AlphaComposite;import java.awt.Color;import java.awt.Font;import java.awt.FontMetrics;import java.awt.Graphics2D;import java.awt.RenderingHints;import java.awt.geom.AffineTransform;import java.awt.image.BufferedImage;import java.io.File;import java.util.Iterator;import javax.imageio.IIOImage;import javax.imageio.ImageIO;import javax.imageio.ImageReader;import javax.imageio.ImageWriteParam;import javax.imageio.ImageWriter;import javax.imageio.stream.FileImageInputStream;import javax.imageio.stream.FileImageOutputStream;import org.junit.Test;public class Wjt {@Testpublic void t3() throws Exception {File rootDir = new File("C:/Users/Administrator/Desktop/tem1");String[] fa = { "1.png", "2.jpg" };for (String s : fa) {String f = s;{FileImageInputStream fileImageInputStream = new FileImageInputStream(new File(rootDir, f));Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(fileImageInputStream); //根据图⽚⽂件获取读取器ImageReader imageReader = imageReaders.hasNext() ? imageReaders.next() : null; //检测读取器是否存在imageReader.setInput(fileImageInputStream); //设置读取器输⼊流BufferedImage bufferedImage = imageReader.read(0); //从读取器取BufferedImage,这⾥只有⼀个,所以可以直接写0{ //开始加⽔印Graphics2D graphics2d = bufferedImage.createGraphics(); //取画笔graphics2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); //设置画笔⽂字抗锯齿graphics2d.transform(AffineTransform.getTranslateInstance(bufferedImage.getWidth() / 2, bufferedImage.getHeight() / 2)); //将画笔移动到图⽚中央graphics2d.transform(AffineTransform.getRotateInstance(Math.toRadians(45))); //将画笔旋转⼀定弧度float radius = Double.valueOf(Math.sqrt(bufferedImage.getWidth() * bufferedImage.getWidth() + bufferedImage.getHeight() * bufferedImage.getHeight()) / 2).floatValue(); //计算图⽚外切圆半径 Font waterMarkerFont = new Font("微软雅⿊", Font.PLAIN, bufferedImage.getHeight() / 25); //设置画笔要⽤的字体,这⾥可以设置字体样式和⼤⼩graphics2d.setFont(waterMarkerFont); //设置画笔字体graphics2d.setColor(Color.WHITE); //设置画笔颜⾊graphics2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.3F)); //设置画笔操作透明度FontMetrics fontMetrics = graphics2d.getFontMetrics(); //取画笔字体信息String waterMarker = "THIS IS WATERMARK."; //⽔印⽂字int stringWidth = fontMetrics.stringWidth(waterMarker); //计算⽔印⽂字宽度,很多⼈卡在了这⼀步for (float i = -radius; i <= radius; i += (stringWidth + bufferedImage.getHeight() / 25)) { //循环添加⽔印,这⾥可以设置⽔印⽔平距离,单位:pxfor (float j = -radius; j <= radius; j += (fontMetrics.getHeight() + bufferedImage.getHeight() / 25)) { //这⾥可以设置⽔印垂直距离,单位:pxgraphics2d.drawString(waterMarker, i, j); //画⽔印}}graphics2d.dispose(); //释放画笔资源}ImageWriter imageWriter = ImageIO.getImageWriter(imageReader); //根据图⽚⽂件读取器获取图⽚⽂件写⼊器String[] split = f.split("\\.");FileImageOutputStream fileOutputStream = new FileImageOutputStream(new File(rootDir, split[0] + "r." + split[1])); //⽣成⽬标图⽚⽂件路径imageWriter.setOutput(fileOutputStream); //设置写⼊器输出流IIOImage iioImage = new IIOImage(bufferedImage, null, null);ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();if (imageReader.getFormatName().equals("JPEG")) { //jpg格式图⽚可设置输出图⽚⽂件的质量imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); //这⼀⾏固定这样写,跟下⼀⾏搭配imageWriteParam.setCompressionQuality(0.947F); //跟上⼀⾏搭配,设置输出图⽚⽂件的质量}imageWriter.write(null, iioImage, imageWriteParam); //写⽂件imageWriter.dispose(); //关闭写⼊器imageReader.dispose(); //关闭读取器}}}}代码流程在注释中写的很详细了,不多做解释。
Java图像处理:使用Java 2D API实现图片处理
Java图像处理:使用Java 2D API实现图片处理引言:随着数字摄影技术的发展,我们每天都会拍摄大量的照片。
然而,有时候我们可能需要对这些照片进行一些处理,以使它们更加美观或符合特定的需求。
在本文中,我们将介绍如何使用Java 2D API来实现图片处理,帮助您更好地处理和优化您的图片。
第一部分:Java 2D API简介Java 2D API是Java平台中用于处理图形和图像的强大工具。
它提供了一组丰富的类和方法,使我们能够创建和操作各种图形对象,如线条、矩形、多边形和图像。
Java 2D API还支持图形渲染、颜色管理和图像转换等高级功能。
第二部分:加载和显示图片在开始处理图片之前,我们首先需要加载和显示图片。
Java 2D API提供了Image类来处理图像。
我们可以使用ImageIO类的静态方法read()来从文件中读取图像,并将其保存在一个Image对象中。
然后,我们可以使用Graphics类的drawImage()方法将图像绘制到指定的位置上。
第三部分:图片缩放有时候,我们可能需要调整图片的大小,使其适应特定的显示区域或满足特定的要求。
Java 2D API提供了AffineTransform类来处理图像的变换操作。
我们可以使用AffineTransform类的scale()方法来缩放图像。
通过指定缩放因子,我们可以按比例增加或减小图像的大小。
第四部分:图片旋转除了缩放,有时候我们还需要将图片旋转一定角度。
Java 2D API同样提供了AffineTransform类来实现图像的旋转操作。
我们可以使用AffineTransform类的rotate()方法来指定旋转的角度,并将其应用于图像。
第五部分:图片滤镜效果为了给图片增加一些特殊的效果,Java 2D API提供了一些内置的滤镜类。
我们可以使用这些滤镜类来对图像进行模糊、锐化、亮度调整等操作。
通过创建一个Filter对象,并将其应用于图像,我们可以很容易地实现这些效果。
hutool 水印偏移量
hutool 水印偏移量Hutool 是一个Java工具包,提供了一系列的工具方法和函数,方便开发者进行Java 编程。
其中也包含了图片处理的工具类,用来进行图片的水印操作。
在Hutool 中,水印偏移量指的是水印在图片上的位置偏移量,即水印相对于图片左上角的位置偏移坐标。
可以通过设置偏移量来调整水印在图片上的位置。
以下是一个使用 Hutool 进行图片水印操作,并设置偏移量的示例代码:```javaimport cn.hutool.core.img.Img;import cn.hutool.core.io.FileUtil;import cn.hutool.core.io.IoUtil;import cn.hutool.core.util.ImageUtil;import java.awt.Font;import java.awt.Color;public class WatermarkExample {public static void main(String[] args) {String imagePath = "path/to/image.jpg";String watermarkText = "Watermark";int offsetX = 10; // x 偏移量int offsetY = 10; // y 偏移量// 加载图片Img img = Img.from(FileUtil.file(imagePath));// 设置水印字体样式和颜色Font font = new Font("Arial", Font.BOLD, 50);Color color = Color.RED;// 添加水印img.pressText(ImgUtil.modifyFont(font), watermarkText, color, new Pos(offsetX, offsetY), 0.8f);// 输出水印图片img.write(FileUtil.file("path/to/output.jpg"));}}```在上述代码中,我们使用 `Img.from` 方法加载图片,然后使用`pressText` 方法给图片添加文本水印。
详解javagoogleThumbnails图片处理
详解javagoogleThumbnails图⽚处理在后端开发的过程中,都逃不开与⽂件传输特别是图⽚的传输打交道,但是因为现在各种拍照设备发展越来越快,拍出的照⽚更是越来越清晰,但是照⽚⽂件的⼤⼩也是越来越⼤了,⼿机拍照⼩则2M⼤则30M这在⽹络传输过程中谁顶得住呀!所以在⽤户发布照⽚,后端对图像⽂件进⾏保存的过程中压缩图像⽂件是必不可少的⼀个过程。
⽽Thumbnails就是⼀个很好的图像处理⼯具,他把复杂的图像处理封装的很好,只需要短短的⼀⾏代码就能完成对图像的压缩。
Thumbnails⽀持:指定⼤⼩进⾏缩放按照⽐例进⾏缩放不按照⽐例,指定⼤⼩进⾏缩放旋转⽔印裁剪转化图像格式输出到OutputStream输出到BufferedImage输出到ByteArrayOutputStream(OutputStream)输出到ByteArrayInputStream(InputStream)输出到byte[]Thumbnails导⼊依赖<dependency><groupId>net.coobird</groupId><artifactId>thumbnailator</artifactId><version>0.4.8</version></dependency>⼀,指定⼤⼩进⾏缩放//size(宽度, ⾼度)/** 若图⽚横⽐200⼩,⾼⽐300⼩,不变* 若图⽚横⽐200⼩,⾼⽐300⼤,⾼缩⼩到300,图⽚⽐例不变* 若图⽚横⽐200⼤,⾼⽐300⼩,横缩⼩到200,图⽚⽐例不变* 若图⽚横⽐200⼤,⾼⽐300⼤,图⽚按⽐例缩⼩,横为200或⾼为300*/Thumbnails.of("images/a380_1280x1024.jpg").size(200, 300).toFile("c:/a380_200x300.jpg");Thumbnails.of("images/a380_1280x1024.jpg").size(2560, 2048).toFile("c:/a380_2560x2048.jpg");⼆,单个图⽚等⽐例缩放File file = new File("c:\\test.png");Thumbnails.of(new FileInputStream(file)).scale(3.0).toFile(new File("c:\\yyyyy.png"));3.0是⼀个double类型的数字,缩放⽐例,⼤于1就是变⼤,⼩于1就是缩⼩三,不按照⽐例,指定⼤⼩进⾏缩放//keepAspectRatio(false) 默认是按照⽐例缩放的Thumbnails.of("images/a380_1280x1024.jpg").size(200, 200).keepAspectRatio(false).toFile("c:/a380_200x200.jpg");四,批量产⽣缩略图Thumbnails.of(new File("D:\\pics").listFiles()).scale(0.2).outputFormat("png").toFiles(Rename.PREFIX_DOT_THUMBNAIL);五,控制图⽚质量,图⽚尺⼨不变File fromPic = new File("C:\\Users\\Administrator\\Desktop\\IdCardPositive_987136936_1531741954688.jpeg");File toPic =new File("C:\\Users\\Administrator\\Desktop\\IdCardPositive_987136936_08.jpeg");Thumbnails.of(fromPic).scale(1f).outputQuality(0.25f).toFile(toPic);outputQuality就是⽤来控制图⽚质量的六,给图⽚加⽔印Thumbnails.of(fromPic).scale(0.8).watermark(Positions.BOTTOM_RIGHT, ImageIO.read(waterPic), 0.5f).outputQuality(0.8f).toFile(toPic);//watermark(位置,⽔印图,透明度)Thumbnails.of("images/a380_1280x1024.jpg").size(1280, 1024).watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File("images/watermark.png")), 0.5f).outputQuality(0.8f).toFile("c:/a380_watermark_bottom_right.jpg");Thumbnails.of("images/a380_1280x1024.jpg").size(1280, 1024).watermark(Positions.CENTER, ImageIO.read(new File("images/watermark.png")), 0.5f).outputQuality(0.8f).toFile("c:/a380_watermark_center.jpg");fromPic是原图,waterPic是⽔印图⽚,toPic是⽣成后的图⽚七,旋转图⽚Thumbnails.of(fromPic).scale(0.5).rotate(90).toFile(toPic);⼋,图⽚裁剪Thumbnails.of(fromPic).sourceRegion(Positions.CENTER, 300, 300).scale(1.0).toFile(toPic);//sourceRegion()//图⽚中⼼400*400的区域Thumbnails.of("images/a380_1280x1024.jpg").sourceRegion(Positions.CENTER, 400,400).size(200, 200).keepAspectRatio(false).toFile("c:/a380_region_center.jpg");//图⽚右下400*400的区域Thumbnails.of("images/a380_1280x1024.jpg").sourceRegion(Positions.BOTTOM_RIGHT, 400,400).size(200, 200).keepAspectRatio(false).toFile("c:/a380_region_bootom_right.jpg");//指定坐标Thumbnails.of("images/a380_1280x1024.jpg").sourceRegion(600, 500, 400, 400).size(200, 200).keepAspectRatio(false).toFile("c:/a380_region_coord.jpg");九,WEB输出流图⽚某些应⽤上传的图⽚可能质量⽐较⾼,但是⽤户在列表浏览的时候,⼜不想原图展⽰,因为带宽要求较⾼,此时可以降低图⽚质量(上⾯提到的outputQuality),以outputstream输出流的⽅式response给浏览器去展⽰@RequestMapping("/getImages")public void getImages(HttpServletRequest request, HttpServletResponse response) throws IOException {Thumbnails.of("images/a380_1280x1024.jpg").scale(1f).outputQuality(0.5f).outputFormat("jpg").toOutputStream(response.getOutputStream());}⼗,图像的格式转换//outputFormat(图像格式)Thumbnails.of("images/a380_1280x1024.jpg").size(1280, 1024).outputFormat("png").toFile("c:/a380_1280x1024.png");Thumbnails.of("images/a380_1280x1024.jpg").size(1280, 1024).outputFormat("gif").toFile("c:/a380_1280x1024.gif");⼗⼀,输出到BufferedImage//asBufferedImage() 返回BufferedImageBufferedImage thumbnail = Thumbnails.of("images/a380_1280x1024.jpg").size(1280, 1024).asBufferedImage();ImageIO.write(thumbnail, "jpg", new File("c:/a380_1280x1024_BufferedImage.jpg"));⼗⼆,输出到ByteArrayOutputStream(OutputStream)ByteArrayOutputStream thumbnailOutputStream = new ByteArrayOutputStream();Thumbnails.of("images/a380_1280x1024.jpg").scale(1f).outputQuality(0.5f).outputFormat("jpg").toOutputStream(thumbnailOutputStream);⼗三,输出到ByteArrayInputStream(InputStream)ByteArrayOutputStream thumbnailOutputStream = new ByteArrayOutputStream();Thumbnails.of("images/a380_1280x1024.jpg").scale(1f).outputQuality(0.5f).outputFormat("jpg").toOutputStream(thumbnailOutputStream);ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(thumbnailOutputStream.toByteArray());⼗三,输出到byte[]ByteArrayOutputStream handlerOutputStream = new ByteArrayOutputStream();Thumbnails.of(inputStream).scale(1f).outputQuality(0.25f).outputFormat("jpg").toOutputStream(handlerOutputStream);byte[] bytes = handlerOutputStream.toByteArray();到此这篇关于java google Thumbnails 图⽚处理的⽂章就介绍到这了,更多相关java google Thumbnails 图⽚处理内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。
Java在Excel中添加水印的实现(单一水印、平铺水印)
Java在Excel中添加⽔印的实现(单⼀⽔印、平铺⽔印)在Excel中没有直接添加⽔印的功能,但依旧可以通过⼀定⽅式来实现类似⽔印效果。
本⽂通过Java程序代码介绍具体实现⽅法。
可添加单⼀⽔印效果,即⽔印是以单个⽂本字样来呈现;也可添加多个平铺⽔印效果,即⽔印是以多个⽂本字样来页⾯中平铺。
详细内容见下⽂。
程序环境:测试⽂档:Office Excel 2013编译环境:IntelliJ IDEA 2018JDK版本:1.8.0Excel库:Java系列 spire.xls.jar 3.9.11.单⼀⽔印效果import com.spire.xls.*;import java.awt.*;import java.awt.image.BufferedImage;import static java.awt.image.BufferedImage.TYPE_INT_ARGB;public class SingleWatermark {public static void main(String[] args) {//加载Excel测试⽂档Workbook wb = new Workbook();wb.loadFromFile("test.xlsx");//设置⽂本和字体⼤⼩Font font = new Font("仿宋", Font.PLAIN, 40);for (int i =0;i<wb.getWorksheets().getCount();i++){Worksheet sheet = wb.getWorksheets().get(i);//调⽤DrawText() ⽅法插⼊图⽚BufferedImage imgWtrmrk = drawText("内部专⽤", font, Color.pink, Color.white, sheet.getPageSetup().getPageHeight(), sheet.getPageSetup().getPageWidth());//将图⽚设置为页眉sheet.getPageSetup().setCenterHeaderImage(imgWtrmrk);sheet.getPageSetup().setCenterHeader("&G");//将显⽰模式设置为Layoutsheet.setViewMode(yout);}//保存⽂档wb.saveToFile("SingleWatermark.xlsx", ExcelVersion.Version2013);}private static BufferedImage drawText (String text, Font font, Color textColor, Color backColor,double height, double width){//定义图⽚宽度和⾼度BufferedImage img = new BufferedImage((int) width, (int) height, TYPE_INT_ARGB);Graphics2D loGraphic = img.createGraphics();//获取⽂本sizeFontMetrics loFontMetrics = loGraphic.getFontMetrics(font);int liStrWidth = loFontMetrics.stringWidth(text);int liStrHeight = loFontMetrics.getHeight();//⽂本显⽰样式及位置loGraphic.setColor(backColor);loGraphic.fillRect(0, 0, (int) width, (int) height);loGraphic.translate(((int) width - liStrWidth) / 2, ((int) height - liStrHeight) / 2);loGraphic.rotate(Math.toRadians(-45));loGraphic.translate(-((int) width - liStrWidth) / 2, -((int) height - liStrHeight) / 2);loGraphic.setFont(font);loGraphic.setColor(textColor);loGraphic.drawString(text, ((int) width - liStrWidth) / 2, ((int) height - liStrHeight) / 2);loGraphic.dispose();return img;}}单⼀⽔印效果:2.平铺⽔印效果import com.spire.xls.*;import java.awt.*;import java.awt.image.BufferedImage;import static java.awt.image.BufferedImage.TYPE_INT_ARGB;public class TiledWatermark {public static void main(String[] args) {//加载Excel测试⽂档Workbook wb = new Workbook();wb.loadFromFile("test.xlsx");//设置⽂本和字体⼤⼩Font font = new Font("仿宋", Font.PLAIN, 25);for (int i =0;i<wb.getWorksheets().getCount();i++){Worksheet sheet = wb.getWorksheets().get(i);//调⽤DrawText() ⽅法插⼊图⽚BufferedImage imgWtrmrk = drawText("内部专⽤内部专⽤内部专⽤内部专⽤", font, Color.pink, Color.white, sheet.getPageSetup().getPageHeight(), sheet.getPageSetup().getPageWidth()); //将图⽚设置为页眉sheet.getPageSetup().setCenterHeaderImage(imgWtrmrk);sheet.getPageSetup().setCenterHeader("&G");//将显⽰模式设置为Layoutsheet.setViewMode(yout);}//保存⽂档wb.saveToFile("TiledWatermark.xlsx", ExcelVersion.Version2013);}private static BufferedImage drawText (String text, Font font, Color textColor, Color backColor,double height, double width){//定义图⽚宽度和⾼度BufferedImage img = new BufferedImage((int) width, (int) height, TYPE_INT_ARGB);Graphics2D loGraphic = img.createGraphics();//获取⽂本sizeFontMetrics loFontMetrics = loGraphic.getFontMetrics(font);int liStrWidth = loFontMetrics.stringWidth(text);int liStrHeight = loFontMetrics.getHeight();//⽂本显⽰样式及位置loGraphic.setColor(backColor);loGraphic.fillRect(0, 0, (int) width, (int) height);loGraphic.translate(((int) width - liStrWidth) / 2, ((int) height - liStrHeight) / 2);//loGraphic.rotate(Math.toRadians(-45));loGraphic.translate(-((int) width - liStrWidth) / 2, -((int) height - liStrHeight) / 2);loGraphic.setFont(font);loGraphic.setColor(textColor);loGraphic.drawString(text, ((int) width - liStrWidth) /6 , ((int) height - liStrHeight) /6);loGraphic.drawString(text,((int) width - liStrWidth) /3, ((int) height - liStrHeight) /3);loGraphic.drawString(text,((int) width - liStrWidth) /2, ((int) height - liStrHeight) /2);loGraphic.dispose();return img;}}平铺⽔印效果:★需要注意的是:在添加完⽔印效果后,查看⽂档时,在“普通视图”⽔印不可见,需在“页⾯布局”模式或“打印预览”模式下查看。
Java 在PDF中添加文本水印和图片水印_基于Spire.Cloud.SDK for Java
Java 在PDF中添加文本水印、图片水印(基于Spire.Cloud.SDK for Java)Spire.Cloud.SDK for Java提供了接口pdfWartermarkApi可用于添加文本水印addTextWartermark()和图片水印addImageWartermark()到PDF文档。
文本将通过Java示例介绍具体实现方法。
首先请参考以下步骤准备程序运行环境:一、导入jar文件。
(有2种方式)(推荐)方式1. 创建Maven项目程序,通过maven仓库下载导入。
以IDEA为例,新建Maven项目,在xml文件中配置maven仓库路径,并指定spire.cloud.sdk的依赖,如下:<repositories><repository><id>com.e-iceblue</id><name>cloud</name><url>/repository/maven-public/</url></repository></repositories><dependencies><dependency><groupId> cloud </groupId><artifactId>spire.cloud.sdk</artifactId><version>3.5.0</version></dependency><dependency><groupId> com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.8.1</version></dependency><dependency><groupId> com.squareup.okhttp</groupId><artifactId>logging-interceptor</artifactId><version>2.7.5</version></dependency><dependency><groupId> com.squareup.okhttp </groupId><artifactId>okhttp</artifactId><version>2.7.5</version></dependency><dependency><groupId> com.squareup.okio </groupId><artifactId>okio</artifactId><version>1.6.0</version></dependency><dependency><groupId> io.gsonfire</groupId><artifactId>gson-fire</artifactId><version>1.8.0</version></dependency><dependency><groupId>io.swagger</groupId><artifactId>swagger-annotations</artifactId><version>1.5.18</version></dependency><dependency><groupId> org.threeten </groupId><artifactId>threetenbp</artifactId><version>1.3.5</version></dependency></dependencies>完成配置后,点击“Import Changes” 即可导入所有需要的jar文件。
Java 如何在PDF文档中添加水印
Java在PDF中添加水印(文本/图片水印)水印是一种十分常用的防伪手段,常用于各种文档、资料等。
常见的水印,包括文字类型的水印、图片或logo类型的水印。
以下Java示例,将分别使用insertTextWatermark(PdfPageBase page, String watermark)方法以及page.SetBackgroundImage(String arg0)方法来设置文本水印和图片水印。
下面将演示具体的代码操作,内容供参考。
工具:Spire.PDF for Java文件引用:步骤1:首先,在Java程序中新建一个文件夹可命名为Lib。
下载安装Spire.PDF for Java 的包后,解压,将解压后的文件夹下的子文件夹lib中的Spire.Pdf.jar和mon.jar 两个文件复制到新建的文件夹下,如下图:步骤2:建好文件夹后,引用两个文件:选中这两个文件,点击鼠标右键,选择“Build Path”–“Add to Build Path”。
Java代码示例(供参考)【示例1】添加文本水印import com.spire.pdf.*;import com.spire.pdf.graphics.*;import java.awt.*;import java.awt.geom.*;public class Textwatermark {public static void main(String[] args) {//创建PdfDocument类的对象PdfDocument pdf = new PdfDocument();//加载测试文档pdf.loadFromFile("test.pdf");//获取测试文档中的第一页PdfPageBase page = pdf.getPages().get(0);//调用insertWatermark()方法添加文本水印insertWatermark(page, "TOP SECRET");//保存文档pdf.saveToFile("out/textWaterMark.pdf");}static void insertWatermark(PdfPageBase page, String watermark)Dimension2D dimension2D = new Dimension();dimension2D.setSize(page.getCanvas().getClientSize().getWidt h() / 2, page.getCanvas().getClientSize().getHeight() / 2); PdfTilingBrush brush = new PdfTilingBrush(dimension2D); brush.getGraphics().setTransparency(0.4F);brush.getGraphics().save();brush.getGraphics().translateTransform((float)brush.getSize().getWidth() / 2, (float)brush.getSize().getHeight() / 2);brush.getGraphics().rotateTransform(-45);brush.getGraphics().drawString(watermark, newPdfFont(PdfFontFamily.Helvetica, 30), PdfBrushes.getViolet(), 0 , 0 , new PdfStringFormat(PdfTextAlignment.Center)); brush.getGraphics().restore();brush.getGraphics().setTransparency(1);Rectangle2D loRect = new Rectangle2D.Float();loRect.setFrame(new Point2D.Float(0, 0),page.getCanvas().getClientSize());page.getCanvas().drawRectangle(brush, loRect);}}文本水印添加效果:【示例2】添加图片水印import com.spire.pdf.*;import java.awt.geom.Rectangle2D;public class watermark {public static void main(String[] args) {//实例化PdfDocument类的对象,并加载测试文档PdfDocument doc = new PdfDocument();doc.loadFromFile("test.pdf");//获取文档第1页PdfPageBase page = doc.getPages().get(0);//加载图片,设置为背景水印page.setBackgroundImage("logo.png");//指定水印在文档中的位置及图片大小Rectangle2D.Float rect = new Rectangle2D.Float(); rect.setRect(150, 150, 300, 150);page.setBackgroundRegion(rect);//保存文档doc.saveToFile("output/imageWaterMark.pdf"); doc.close();}}图片水印添加效果:(本文完)。
Java通过POI和JXL给Excel动态添加水印
一:设置水印要显示的model类(非必要)package zp.ExcelUtil;import java.text.SimpleDateFormat;import java.util.Date;public class Model {private String ip;private String user;private Date date;public Model() {// TODO Auto-generated constructor stub}public Model(String ip, String user, Date date) {this.ip = ip;er = user;this.date = date;}public String getIp() {return ip;}public void setIp(String ip) {this.ip = ip;}public String getUser() {return user;}public void setUser(String user) {er = user;}public String getDate() {SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");return sdf.format(date);}public void setDate(Date date) {this.date = date;}}二.编写工具类package zp.ExcelUtil;import java.awt.AlphaComposite;import java.awt.BasicStroke;import java.awt.Color;import java.awt.Font;import java.awt.Graphics2D;import java.awt.font.FontRenderContext;import java.awt.geom.Rectangle2D;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import ng.reflect.Method;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import javax.imageio.ImageIO;import org.json.JSONException;import org.json.JSONObject;public class Utilss {private static int width = 900; // 水印图片的宽度private static int height = 1020; // 水印图片的高度因为设置其他的高度会有黑线,所以拉高高度/*** 将JavaBean转换成JSONObject(通过Map中转)** @param bean* javaBean* @return json对象* @throws Exception*/public static JSONObject modelToJSON(Object bean) throws Exception {return new JSONObject(toMap(bean));}/*** 将Javabean转换为Map** @param javaBean* javaBean* @return Map对象*/@SuppressWarnings({ "unchecked", "rawtypes" })public static Map toMap(Object javaBean) throws Exception { Map result = new HashMap();Method[] methods = javaBean.getClass().getDeclaredMethods();for (Method method : methods) {if (method.getName().startsWith("get")) {String field = method.getName();field = field.substring(field.indexOf("get") + 3);field = field.toLowerCase().charAt(0) + field.substring(1);Object value = method.invoke(javaBean, (Object[]) null);result.put(field, null == value ? "" : value.toString());}}return result;}/*** 将Json对象转换成Map** @param jsonObject* json对象* @return Map对象* @throws JSONException*/@SuppressWarnings({ "rawtypes", "unchecked" })public static Map toMap(String jsonString) throws JSONException { JSONObject jsonObject = new JSONObject(jsonString);Map result = new HashMap();Iterator iterator = jsonObject.keys();String key = null;String value = null;while (iterator.hasNext()) {key = (String) iterator.next();value = jsonObject.getString(key);result.put(key, value);}return result;}/*** 生成水印图片** @param watermark* @return* @throws IOException*/public static File createWaterMark(String watermark) throws IOException { int width = 800;int height = 1020;File file = new File("watermark.bmp");Font font = new Font("Serif", Font.ITALIC, 20);BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics2D g2 = bi.createGraphics();// 设置字体颜色为灰色g2.setColor(Color.LIGHT_GRAY);// 设置字体g2.setFont(font);// 设置字体倾斜度g2.rotate(Math.toRadians(0), (double) bi.getWidth() / 2, (double) bi.getHeight() / 2);g2.setBackground(Color.WHITE);g2.clearRect(0, 0, width, height);FontRenderContext context = g2.getFontRenderContext();Rectangle2D bounds = font.getStringBounds(watermark, context);double x = (width - bounds.getWidth()) / 2;double y = (height - bounds.getHeight()) / 2;double ascent = -bounds.getY();double baseY = y + ascent;g2.drawString(watermark, (int) x, (int) baseY);// ImageIO.write(bi, "bmp", file);// 通过bmp写入文件//BMPEncoder.write(bi, file);return file;}@SuppressWarnings({ "rawtypes", "unchecked" })public static Map createWaterMark1(Map watermarkMessage) throws IOException { Map map = new HashMap();File file = new File("watermark.bmp");// 获取bufferedImage对象BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// 处理背景色,设置为白色int minx = bi.getMinX();int miny = bi.getMinY();for (int i = minx; i < width; i++) {for (int j = miny; j < height; j++) {bi.setRGB(i, j, 0xffffff);}}// 获取Graphics2d对象Graphics2D g2d = bi.createGraphics();// 设置字体颜色为灰色g2d.setColor(Color.LIGHT_GRAY);// 设置图片的属性g2d.setStroke(new BasicStroke(1));// 设置字体g2d.setFont(new Font("Serif", Font.ITALIC, 40));// 设置字体倾斜度g2d.rotate(Math.toRadians(-8));// 写入水印文字原定高度过小,所以累计写水印,增加高度for (int i = 1; i < 7; i++) {Object[] key = watermarkMessage.keySet().toArray();for (int j = 0; j < key.length; j++) {if (key[j].equals("date")) {g2d.drawString("日期: " + watermarkMessage.get(key[j]), 0, 180 * i + 40 * (j + 1));} else if (key[j].equals("user")) {g2d.drawString("用户: " + watermarkMessage.get(key[j]), 0, 180 * i + 40 * (j + 1));} else if (key[j].equals("ip")) {g2d.drawString("IP地址: " + watermarkMessage.get(key[j]), 0, 180 * i + 40 * (j + 1));} else {g2d.drawString((String) key[j] + " : " + watermarkMessage.get(key[j]), 0, 180 * i + 40 * (j + 1));}}}// 设置透明度g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));// 释放对象g2d.dispose();// 通过bmp写入文件// BMPEncoder.write(bi, file);ImageIO.write(bi, "bmp", file);map.put("file", file);map.put("width", width);map.put("height", height);return map;}}三.编写处理类package zp.ExcelUtil;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.util.Map;import org.json.JSONObject;import jxl.Workbook;import jxl.write.WritableSheet;import jxl.write.WritableWorkbook;public class ExcelUtil {/**** @param xls_filePath_in 要添加水印的excel文件路径(必须是*.xls文件,如"/in.xls")* @param xls_filePath_out excel文件输出路径(必须是*.xls文件,如"/out.xls")* @param watermarkText* @throws Exception*/@SuppressWarnings("rawtypes")public static void addWatermark(String xls_filePath_in,String xls_filePath_out,JSONObject watermarkText) throws Exception{InputStream is = new FileInputStream(new File(xls_filePath_in));Workbook wb = Workbook.getWorkbook(is); // 获得原始文档WritableWorkbook wwb = Workbook.createWorkbook(new File(xls_filePath_out),wb);WritableSheet ws1 = wwb.getSheet(0);// 得到工作薄中的第一个工作表//String watermarkMessage = jsonObject.toString();Map watermarkMessage = Utilss.toMap(watermarkText.toString());Map map = Utilss.createWaterMark1(watermarkMessage);File fileImg = (File) map.get("file");//File fileImg = new File("kkkk.bmp");byte imageData[] = new byte[(int) fileImg.length()];FileInputStream fis = new FileInputStream(fileImg);fis.read(imageData);// must be 24 bit true-colour,bmp file// * @param imageByte// * @param widthPixel// * @param heightPixelws1.setWaterMarkImage(imageData, (int)map.get("width"), (int)map.get("height"));wwb.write();wwb.close();fis.close();}}四.测试package zp.ExcelUtil;import java.util.Date;import org.json.JSONObject;public class test {public static void main(String[] args) throws Exception {Model model = new Model("1.1.1.1", "tom", new Date());JSONObject jo = Utilss.modelToJSON(model);ExcelUtil.addWatermark("in.xls", "out.xls", jo);}}。
Java 添加、删除Word水印
Java 添加、删除Word水印水印是一种常用于各种文档的声明、防伪手段,一般可设置文字水印或者加载图片作为水印。
以下内容将分享通过Java编程给Word文档添加水印效果的方法,以及如何将Word文档中已有的水印效果删除。
使用工具:Free Spire.Doc for Java 2.0.0(免费版)Jar导入:方法1:通过官网下载控件包。
在程序下新建一个directory目录,并命名(本示例中命名为lib);将控件包lib文件夹下的jar(如下图1)复制到程序中新建的目录下。
复制jar文件后,鼠标右键点击jar文件,选择”A dd as Library”。
完成导入(如下图2)。
图1:图2:方法2:通过maven导入。
参考导入方法。
Java代码示例(供参考)【示例1】添加文本水印import com.spire.doc.*;import com.spire.doc.documents.WatermarkLayout; import java.awt.*;public class Main {public static void main(String[] args) { //加载测试文档Document document = new Document();document.loadFromFile("sample.docx");//插入水印InsertTextWatermark(document.getSections().get(0));//保存文档document.saveToFile("textwatermark.docx",FileFormat.Docx ); }//自定义方法用于指定文本水印字样及格式化操作private static void InsertTextWatermark(Section section){TextWatermark txtWatermark = new TextWatermark();txtWatermark.setText("内部使用");txtWatermark.setFontSize(40);txtWatermark.setColor(Color.red);txtWatermark.setLayout(WatermarkLayout.Diagonal);section.getDocument().setWatermark(txtWatermark);}文本水印效果:【示例2】添加图片水印import com.spire.doc.*;public class Main {public static void main(String[] args) {//加载测试文档Document document = new Document();document.loadFromFile("sample.docx");//加载图片设置为水印PictureWatermark picture = new PictureWatermark();picture.setPicture("wx.png");picture.setScaling(5);picture.isWashout(false);document.setWatermark(picture);//保存文档document.saveToFile("imagewatermark.docx",FileFormat.Docx ); }}图片水印效果:【示例3】删除Word水印import com.spire.doc.*;public class DeleteWatermark {public static void main(String[] args){//加载含有水印的Word文档Document doc = new Document("test.docx");//调用方法setWatermark()设置为null,去掉水印效果doc.setWatermark(null);//保存文档doc.saveToFile("result.docx",FileFormat.Docx_2010); }}运行程序后,水印效果将被删除。
Java实现给图片添加图片水印,文字水印及马赛克的方法示例
Java实现给图⽚添加图⽚⽔印,⽂字⽔印及马赛克的⽅法⽰例本⽂实例讲述了Java实现给图⽚添加图⽚⽔印,⽂字⽔印及马赛克的⽅法。
分享给⼤家供⼤家参考,具体如下:可以在eclipse中新建个Utils类,把以下代码复制进去直接使⽤,以下⽅法实现单个或多个⽔印的添加package mon.util;import java.awt.AlphaComposite;import java.awt.Color;import java.awt.Font;import java.awt.Graphics2D;import java.awt.Image;import java.awt.RenderingHints;import java.awt.image.BufferedImage;import java.io.File;import javax.imageio.ImageIO;import javax.swing.ImageIcon;/*** 给图⽚添加⽔印* @author tgy**/public class MarkImageUtils {/*** @param args*/public static void main(String[] args) {String output = "F:/images/";String source = "F:/images/6.jpg"; //源图⽚路径String icon = "F:/images/icon2.png"; //覆盖图⽚路径String imageName = "mark_image"; //图⽚名称String imageType = "jpg"; //图⽚类型jpg,jpeg,png,gifString text = "加⽔印了";int size = 4; //马赛克⼤⼩Integer degree = null; //⽔印旋转⾓度-45,null表⽰不旋转String result = null;//给图⽚添加图⽚⽔印result = MarkImageUtils.markImageByMoreIcon(icon,source,output,imageName,imageType,degree);// result = MarkImageUtils.markImageBySingleIcon(icon, source, output, imageName, imageType, degree);// //给图⽚添加⽂字⽔印// result = MarkImageUtils.markImageByMoreText(source,output,imageName,imageType,Color.red,text,degree);// result = MarkImageUtils.markImageBySingleText(source,output,imageName,imageType,Color.red,text,degree);// //给图⽚打马赛克// result = MarkImageUtils.markImageByMosaic(source,output,imageName,imageType,size);System.out.println(result);}/*** 给图⽚不同位置添加多个图⽚⽔印、可设置⽔印图⽚旋转⾓度* @param icon ⽔印图⽚路径(如:F:/images/icon.png)* @param source 没有加⽔印的图⽚路径(如:F:/images/6.jpg)* @param output 加⽔印后的图⽚路径(如:F:/images/)* @param imageName 图⽚名称(如:11111)* @param imageType 图⽚类型(如:jpg)* @param degree ⽔印图⽚旋转⾓度,为null表⽰不旋转*/public static String markImageByMoreIcon(String icon,String source,String output,String imageName,String imageType,Integer degree) {String result = "添加图⽚⽔印出错";try {File file = new File(source);File ficon = new File(icon);if (!file.isFile()) {return source + " 不是⼀个图⽚⽂件!";}//将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/3int 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对象。
Java实现为Word每一页设置不同图片水印的效果
Java实现为Word每⼀页设置不同图⽚⽔印的效果⽬录⽅法思路Jar引⼊Java代码⽰例代码补充Word中设置⽔印时,可加载图⽚设置为⽔印效果,但通常添加⽔印效果时,会对所有页⾯都设置成统⼀效果,如果需要对每⼀页或者某个页⾯设置不同的⽔印效果,则可以参考本⽂中的⽅法。
下⾯,将以Java代码为例,对Word每⼀页设置不同的图⽚⽔印效果作详细介绍。
⽅法思路在给Word每⼀页添加⽔印前,⾸先需要在Word⽂档每⼀页正⽂的最后⼀个字符后⾯插⼊“连续”分节符,然后在每⼀节的页眉段落⾥添加⽔印图⽚,并设置图⽚的坐标位置、对齐⽅式、衬与⽂字下⽅等。
最后保存⽂档。
Jar引⼊在程序中引⼊中的Spire.Doc.jar⽂件(该⽂件在lib⽂件夹下);如果需要通过下载导⼊,可进⾏如下配置pom.xml:<repositories><repository><id>com.e-iceblue</id><url>https:///repository/maven-public/</url></repository></repositories><dependencies><dependency><groupId>e-iceblue</groupId><artifactId>spire.doc.free</artifactId><version>5.1.0</version></dependency></dependencies>Java代码给每页添加图⽚⽔印时,可参考如下步骤:创建Document类的对象,并通过Document.loadFromFile(String fileName)⽅法加载Word⽂档。
通过Document.getSections().get(int index)⽅法获取指定节。
JAVA 处理图片水印
package com.cari.image;/****/import java.awt.AlphaComposite;import java.awt.Color;import java.awt.Graphics2D;import java.awt.Image;import java.awt.image.*;import java.io.*;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import javax.swing.*;import com.sun.image.codec.jpeg.*;/*** @author zsy**/public class WaterMark {private static List logoImgs;private static List bgImgs ;private static float logoPosition = 1f;private static float logoSrcOver = 0.4f;private static float bgSrcOver = 0.3f;private static boolean flag;//为true时生成背景水印,为false 时生成图标水印public static List getBgImgs() {return bgImgs;}/*** 设置背景水印图片的路径并把图片加载到内存* @param bgImgUrls* @param path*/public static void setBgImgs(List bgImgUrls, String path) { bgImgs = new ArrayList();for (Iterator it = bgImgUrls.iterator(); it.hasNext(); ) {String tem = (String)it.next();ImageIcon waterIcon = new ImageIcon(path + tem);bgImgs.add(waterIcon.getImage());}}public static List getLogoImgs() {return logoImgs;}/*** 设置图标水印图片的路径并把图片加载到内存* @param logoImgUrls* @param path*/public static void setLogoImgs(List logoImgUrls, String path) { logoImgs = new ArrayList();for (Iterator it = logoImgUrls.iterator();it.hasNext(); ) {String tem = (String)it.next();ImageIcon waterIcon = new ImageIcon(path + tem);logoImgs.add(waterIcon.getImage());}}public static float getLogoPosition() {return logoPosition;}public static void setLogoPosition(float logoPosition) {WaterMark.logoPosition = logoPosition;}public static float getBgSrcOver() {return bgSrcOver;}public static void setBgSrcOver(float bgSrcOver) {WaterMark.bgSrcOver = bgSrcOver;}public static float getLogoSrcOver() {return logoSrcOver;}public static void setLogoSrcOver(float logoSrcOver) {WaterMark.logoSrcOver = logoSrcOver;}/*** 图片中添加图标水印并输出到指定流* @param data* @param out* @param channel* @return* @throws Exception*/public static boolean createLogoMark(byte[] data,FileOutputStream out, String channel) throws Exception {int i = (int)(logoImgs.size() * Math.random());return createMark(data, out, (Image)logoImgs.get(i), true);}/*** 图片中添加背景水印并输出到指定流* @param data* @param out* @param channelName* @return* @throws Exception*/public static boolean createBgMark(byte[] data,FileOutputStream out, String channelName) throws Exception {int i = (int)(bgImgs.size() * Math.random());return createMark(data, out, (Image)bgImgs.get(i), false);}/*** 生成随机水印并输出到指定流* @param data* @param out* @return* @throws Exception*/public static boolean createRandomMark(byte[] data,FileOutputStream out) throws Exception {int i = 0;Image temImg = null;int logoSize = logoImgs.size();int bgSize = bgImgs.size();if (logoSize <= 0 && bgSize <= 0) {return createMark(data, out, temImg, flag);}if (logoSize <= 0) {flag = true;} else if (bgSize <= 0) {flag = false;}if (!flag) {i = (int)(logoImgs.size() * Math.random());temImg = (Image)logoImgs.get(i);} else {i = (int)(bgImgs.size() * Math.random());temImg = (Image)bgImgs.get(i);}flag = !flag;return createMark(data, out, temImg, flag);}/*** 生成水印并输出到指定流* @param data 图片的二进制数据* @param out 处理后图片的输出流* @param waterImg 水印图片的类型(背景或图标),应与isLogoImg 参数一致,如果为空不加水印* @param isLogoImg 等于true 时生成图标水印,否则为背景水印* @return* @throws Exception*/private static boolean createMark(byte[] data, FileOutputStream out,Image waterImg ,boolean isLogoImg) throws Exception {ImageIcon imgIcon = new ImageIcon(data);Image theImg = imgIcon.getImage();int width = theImg.getWidth(null);int height = theImg.getHeight(null);int w = waterImg == null ? 0 : waterImg.getWidth(null);int h = waterImg == null ? 0 : waterImg.getHeight(null);if (w == 0 || h == 0 || width <= w || height <= h) {//小图片不加水印真接输入,如头像图片BufferedOutputStream fout = null;ByteArrayInputStream in = new ByteArrayInputStream(data);try {byte[] b = new byte[1024*10];fout = new BufferedOutputStream(out);while(in.read(b) > 0) {out.write(b);}out.flush();out.close();in.close();} catch(Exception e) {e.printStackTrace();throw e;} finally {if (in != null) {in.close();}if (fout != null) {fout.close();}}return true;}BufferedImage bimage = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);Graphics2D g = bimage.createGraphics();g.setBackground(Color.white);g.drawImage(theImg, 0, 0, null);if (isLogoImg) {//生成图标水印//设置图片透明度g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, logoSrcOver));width = (int)(width * logoPosition) - w;height = (int)(height * logoPosition) - h;width = width < 0 ? 0 : width;height = height < 0 ? 0 : height;g.drawImage(waterImg, width, height, null);} else {//生成背景水印//'0.2f'设置字体透明度g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, bgSrcOver));int sw = (width % w) /(width / w + 1);//填充水印图片横向间距int sh = (height % h) /(height / h + 1);//填充水印图片纵向间距for(int i = sw; i + w + sw <= width; i += w + sw) {for (int j = sh; j + h + sh <= height; j += h + sh) {g.drawImage(waterImg, i, j, null);}}}g.dispose();try {JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(out);JPEGEncodeParam param =encoder.getDefaultJPEGEncodeParam(bimage);param.setQuality(80f, true);encoder.encode(bimage);} catch (Exception e) {throw e;} finally {if (out != null) {out.close();}}return true;}}。
Java 设置PDF平铺图片背景(水印)
Java 设置PDF平铺图片背景(水印)一、概述及环境准备本文介绍使用免费版PDF库-Free Spire.PDF for Java加载图片来设置成PDF平铺图片背景的效果,也可以作为平铺图片水印来使用;编辑代码前,需要先导入jar文件,有两种方法可供选着导入:1. 手动下载导入:可前往官网下载jar包,并解压,将lib文件夹下的Spire.Pdf.jar文件导入Java程序;2. Maven仓库导入:通过创建Maven项目,在pom.xml文件中配置Maven仓库路径并指定Free Spire.PDF for Java的Maven依赖,如下:<repositories><repository><id>com.e-iceblue</id><url>/repository/maven-public/</url></repository></repositories><dependencies><dependency><groupId> e-iceblue </groupId><artifactId>spire.pdf.free</artifactId><version>2.6.3</version></dependency></dependencies>配置完成后,点击”Import Changes”即可导入Jar文件。
(注:本文中使用的是IDEA,如果使用的是Eclipse,可参考导入方法)Jar导入效果如下:二、Java代码示例import com.spire.pdf.*;import com.spire.pdf.graphics.PdfImage;import com.spire.pdf.graphics.PdfTilingBrush;import java.awt.*;import java.awt.geom.Dimension2D;import java.awt.geom.Rectangle2D;public class AddBackground {public static void main(String[] args) {//创建PdfDocument对象,并加载PDF测试文档PdfDocument pdf = new PdfDocument();pdf.loadFromFile("test.pdf");//遍历文档每一页,加载图片,并设置成平铺背景(水印)for (int i = 0; i < pdf.getPages().getCount();i++){PdfPageBase page = pdf.getPages().get(i);Dimension2D dimension2D = new Dimension();dimension2D.setSize(page.getCanvas().getSize().getWidth()/4,page.getCanvas().getSize().getHeight()/3);PdfTilingBrush brush = new PdfTilingBrush(dimension2D);brush.getGraphics().setTransparency(0.2f);brush.getGraphics().translateTransform(brush.getSize().getWidth()/10,brush.getSize().getHeig ht()/10);brush.getGraphics().rotateTransform(30);PdfImage image = PdfImage.fromImage("logo.png");brush.getGraphics().drawImage(image,brush.getSize().getWidth()-image.getWidth()/2,(brush.getSize().getHeight())/2);Rectangle2D rectangle2D = new Rectangle2D.Float();rectangle2D.setFrame(new Point(0,0),page.getCanvas().getClientSize());page.getCanvas().drawRectangle(brush,rectangle2D);}//保存文档pdf.saveToFile("SetTiledBackground.pdf");pdf.dispose();}}平铺图片背景(水印)效果:(完)。
JavaWeb项目生成PDF文件添加水印图片并导出
JavaWeb项⽬⽣成PDF⽂件添加⽔印图⽚并导出⼀、前⾔⾸先需要在Maven中添加相应的jar包依赖,若项⽬没⽤到Maven,也可⾃⾏下载相应所需的jar包(itextpdf.jar 与 itext-asian.jar),如下图所⽰。
Maven中添加依赖jar包如下所⽰:1<!-- pdf start -->2<dependency>3<groupId>com.itextpdf</groupId>4<artifactId>itextpdf</artifactId>5<version>5.3.2</version>6</dependency>7<dependency>8<groupId>com.itextpdf</groupId>9<artifactId>itext-asian</artifactId>10<version>5.2.0</version>11</dependency>12<!-- pdf end -->⼆、正⽂1、⾸先获取需要填写⾄PDF中的数据,如下述所⽰,realPath为添加图⽚的路径,test.pdf为未添加图⽚的PDF临时⽂件,在Tomcat服务器对应路径下,以及导出的PDF⽂件存⾄桌⾯: 1//点击下载获取企业信息并存⾄Pdf2 @RequestMapping(value="/downloadPdf.do")3 @ResponseBody4public String downloadPdf(@RequestParam(value = "download_corp_id") String download_corp_id, HttpServletRequest request) throws Exception {5 List<TCorp> corpIfs = searchCorpService.getCorpInfo(Integer.parseInt(download_corp_id));6 TCorp tCorp = new TCorp();7for (TCorp corpInfo: corpIfs){8 tCorp.setId(corpInfo.getId());9 tCorp.setRegNo(corpInfo.getRegNo());10 tCorp.setCorpName(corpInfo.getCorpName());11 tCorp.setCorpAddr(corpInfo.getCorpAddr());12 tCorp.setBelongOrg(corpInfo.getBelongOrg());13 tCorp.setBelongDistOrg(corpInfo.getBelongDistOrg());14 tCorp.setBelongTrade(corpInfo.getBelongTrade());15 tCorp.setEconKind(corpInfo.getEconKind());16 tCorp.setAdmitMain(corpInfo.getAdmitMain());17 tCorp.setStartDate(corpInfo.getStartDate());18 tCorp.setCheckDate(corpInfo.getCheckDate());19 tCorp.setOperManIdentNo(corpInfo.getOperManIdentNo());20 tCorp.setOperManName(corpInfo.getOperManName());21 tCorp.setCorpStatus(corpInfo.getCorpStatus());22 tCorp.setRegCapi(corpInfo.getRegCapi());23 tCorp.setPaidCapi(corpInfo.getPaidCapi());24 tCorp.setFareTermStart(corpInfo.getFareTermStart());25 tCorp.setFareTermEnd(corpInfo.getFareTermEnd());26 tCorp.setFareScope(corpInfo.getFareScope());27 tCorp.setUniScid(corpInfo.getUniScid());28 tCorp.setCorpTel(corpInfo.getCorpTel());29 tCorp.setCorpWebUrl(corpInfo.getCorpWebUrl());30 tCorp.setCorpLogo(corpInfo.getCorpLogo());31 tCorp.setCorpEmail(corpInfo.getCorpEmail());32 tCorp.setPracPersonNum(corpInfo.getPracPersonNum());33 tCorp.setOrgInstCode(corpInfo.getOrgInstCode());34 tCorp.setTaxpayNum(corpInfo.getTaxpayNum());35 tCorp.setStaffSize(corpInfo.getStaffSize());36 tCorp.setEnglishName(corpInfo.getEnglishName());37 tCorp.setFormerName(corpInfo.getFormerName());38 tCorp.setCorpInfo(corpInfo.getCorpInfo());39 tCorp.setCreateDate(corpInfo.getCreateDate());40 tCorp.setCreateOrg(corpInfo.getCreateOrg());41 }4243 String realPath = request.getSession().getServletContext().getRealPath("/") + "\\icon\\logo_64.png";44 PDFReport.settCorp(tCorp);45new PDFReport("test.pdf").generatePDF();46 PDFUtil.addImage("test.pdf", "C:\\Users\\Administrator\\Desktop\\"+tCorp.getCorpName()+".pdf",realPath);4748return "提⽰:数据导出成功!";49 }2、PDFReport类中申明⼀个⽂档类型建⽴Document对象,设置页⾯样式等:1package util;23import com.itextpdf.text.Document;4import com.itextpdf.text.PageSize;5import com.itextpdf.text.Rectangle;6import com.itextpdf.text.pdf.PdfPTable;7import com.itextpdf.text.pdf.PdfWriter;8import entity.TCorp;910import java.io.File;11import java.io.FileOutputStream;1213public class PDFReport {14private static TCorp tCorp;1516 Document document = new Document();// 建⽴⼀个Document对象1718public PDFReport(String out) {19try {20 File file = new File(out);21 file.createNewFile();22 Rectangle pageSize = new Rectangle(PageSize.A4);23 document.setPageSize(pageSize);24 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));25 PDFBuilder builder = new PDFBuilder();26 writer.setPageEvent(builder);27 document.open();28 PdfPTable table = generatePDF();29 document.add(table);30 document.close();31 } catch (Exception e) {32 e.printStackTrace();33 }34 }3536public static void settCorp(TCorp tCorp) {37 PDFReport.tCorp = tCorp;38 }394041public PdfPTable generatePDF() {42//设置单元格为5列43 PdfPTable table = PDFUtil.createTable(5);4445 table.addCell(PDFUtil.createHeadCell("企业信息列表"));46 table.addCell(PDFUtil.createTitleCell_1("企业名称"));47 table.addCell(PDFUtil.createCell_1(tCorp.getCorpName()));48 table.addCell(PDFUtil.createTitleCell_1("联系⽅式"));49 table.addCell(PDFUtil.createCell_1(tCorp.getCorpTel()));50 table.addCell(PDFUtil.createCell_2("Logo"));5152 table.addCell(PDFUtil.createTitleCell_1("企业邮箱"));53 table.addCell(PDFUtil.createCell_1(tCorp.getCorpEmail()));54 table.addCell(PDFUtil.createTitleCell_1("⽹址"));55 table.addCell(PDFUtil.createCell_1(tCorp.getCorpWebUrl()));5657 table.addCell(PDFUtil.createTitleCell_1("企业地址"));58 table.addCell(PDFUtil.createCell_1(tCorp.getCorpAddr()));59 table.addCell(PDFUtil.createTitleCell_1("注册/实缴"));60 table.addCell(PDFUtil.createCell_1(String.valueOf(tCorp.getRegCapi())+"万 / "+String.valueOf(tCorp.getPaidCapi())+"万")); 6162 table.addCell(PDFUtil.createTitleCell_1("成⽴⽇期"));63 table.addCell(PDFUtil.createCell_1(tCorp.getStartDate()));64 table.addCell(PDFUtil.createTitleCell_1("统⼀社会信⽤代码"));65 table.addCell(PDFUtil.createCell_3(tCorp.getUniScid()));6667 table.addCell(PDFUtil.createTitleCell_1("法定代表⼈"));68 table.addCell(PDFUtil.createCell_1(tCorp.getOperManName()));69 table.addCell(PDFUtil.createTitleCell_1("纳税⼈识别号"));70 table.addCell(PDFUtil.createCell_3(tCorp.getTaxpayNum()));7172 table.addCell(PDFUtil.createTitleCell_1("注册号"));73 table.addCell(PDFUtil.createCell_1(tCorp.getRegNo()));74 table.addCell(PDFUtil.createTitleCell_1("组织机构代码"));75 table.addCell(PDFUtil.createCell_3(tCorp.getOrgInstCode()));7677 table.addCell(PDFUtil.createTitleCell_1("公司类型"));78 table.addCell(PDFUtil.createCell_1(tCorp.getEconKind()));79 table.addCell(PDFUtil.createTitleCell_1("⼈员规模"));80 table.addCell(PDFUtil.createCell_3(tCorp.getStaffSize()));8182 table.addCell(PDFUtil.createTitleCell_1("营业期限"));83 table.addCell(PDFUtil.createCell_1(tCorp.getFareTermStart()+" ⾄ "+tCorp.getFareTermEnd()));84 table.addCell(PDFUtil.createTitleCell_1("登记机关"));85 table.addCell(PDFUtil.createCell_3(tCorp.getBelongOrg()));8687 table.addCell(PDFUtil.createTitleCell_1("核准⽇期"));88 table.addCell(PDFUtil.createCell_1(tCorp.getCheckDate()));89 table.addCell(PDFUtil.createTitleCell_1("所属⾏业"));90 table.addCell(PDFUtil.createCell_3(tCorp.getBelongTrade()));9192 table.addCell(PDFUtil.createTitleCell_1("英⽂名称"));93 table.addCell(PDFUtil.createCell_1(tCorp.getEnglishName()));94 table.addCell(PDFUtil.createTitleCell_1("曾⽤名"));95 table.addCell(PDFUtil.createCell_3(tCorp.getFormerName()));9697 table.addCell(PDFUtil.createTitleCell_2("经营范围"));98 table.addCell(PDFUtil.createCell_4(tCorp.getFareScope()));99100return table;101 }102 }3、PDFUtil类中设置字体、表格样式、以及⽔印⽂字样式,setColspan函数为设置所跨列数,setRowspan函数为设置所跨⾏数: 1package util;23import com.itextpdf.text.*;4import com.itextpdf.text.pdf.*;56import javax.imageio.ImageIO;7import java.io.BufferedOutputStream;8import java.io.File;9import java.io.FileOutputStream;1011public class PDFUtil {12private static Font headfont ; // 设置字体⼤⼩13private static Font keyfont; // 设置字体⼤⼩14private static Font textfont; // 设置字体⼤⼩1516static{17 BaseFont bfChinese;18try {19 bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);20 headfont = new Font(bfChinese, 24, Font.BOLD,BaseColor.BLACK);// 设置字体⼤⼩21 keyfont = new Font(bfChinese, 12, Font.BOLD,BaseColor.BLACK);// 设置字体⼤⼩22 textfont = new Font(bfChinese, 10, Font.NORMAL,BaseColor.BLACK);// 设置字体⼤⼩23 } catch (Exception e) {24 e.printStackTrace();25 }26 }2728//表格标题29public static PdfPCell createHeadCell(String value){30 PdfPCell cell = new PdfPCell();31 cell.setVerticalAlignment(15);32 cell.setHorizontalAlignment(15);33 cell.setColspan(5);34 cell.setPhrase(new Phrase(value,headfont));35 cell.setHorizontalAlignment(Element.ALIGN_CENTER); //⽔平居中36 cell.setPadding(10.0f);37 cell.setBorder(0);38 cell.setPaddingTop(5.0f);39 cell.setPaddingBottom(18.0f);40return cell;41 }4243//表格表头样式144public static PdfPCell createTitleCell_1(String value){45 PdfPCell cell = new PdfPCell();46 cell.setVerticalAlignment(Element.ALIGN_MIDDLE);47 cell.setHorizontalAlignment(Element.ALIGN_CENTER);48 cell.setPhrase(new Phrase(value, keyfont));49 cell.setBackgroundColor(new BaseColor(29, 181, 238));50 cell.setColspan(1);51 cell.setFixedHeight(35);52return cell;53 }5455//表格表头样式256public static PdfPCell createTitleCell_2(String value){57 PdfPCell cell = new PdfPCell();58 cell.setVerticalAlignment(Element.ALIGN_MIDDLE);59 cell.setHorizontalAlignment(Element.ALIGN_CENTER);60 cell.setPhrase(new Phrase(value, keyfont));61 cell.setBackgroundColor(new BaseColor(29, 181, 238));62 cell.setColspan(1);63 cell.setRowspan(3);64 cell.setFixedHeight(105);65return cell;66 }6768//表格内容样式169public static PdfPCell createCell_1(String value){70 PdfPCell cell = new PdfPCell();71 cell.setVerticalAlignment(Element.ALIGN_MIDDLE);72 cell.setHorizontalAlignment(Element.ALIGN_CENTER);73 cell.setPhrase(new Phrase(value,textfont));74 cell.setBackgroundColor(new BaseColor(255, 255, 255));75 cell.setColspan(1);76 cell.setFixedHeight(35);77return cell;78 }7980//表格内容样式281public static PdfPCell createCell_2(String value){82 PdfPCell cell = new PdfPCell();83 cell.setVerticalAlignment(Element.ALIGN_MIDDLE);84 cell.setHorizontalAlignment(Element.ALIGN_CENTER);85 cell.setPhrase(new Phrase(value,textfont));86 cell.setBackgroundColor(new BaseColor(255, 255, 255));87 cell.setColspan(1);88 cell.setRowspan(3);89 cell.setFixedHeight(105);90return cell;91 }9293//表格内容样式394public static PdfPCell createCell_3(String value){95 PdfPCell cell = new PdfPCell();96 cell.setVerticalAlignment(Element.ALIGN_MIDDLE);97 cell.setHorizontalAlignment(Element.ALIGN_CENTER);98 cell.setPhrase(new Phrase(value,textfont));99 cell.setBackgroundColor(new BaseColor(255, 255, 255));100 cell.setColspan(2);101 cell.setFixedHeight(35);102return cell;103 }104105//表格内容样式4106public static PdfPCell createCell_4(String value){107 PdfPCell cell = new PdfPCell();108 cell.setVerticalAlignment(Element.ALIGN_MIDDLE);109 cell.setHorizontalAlignment(Element.ALIGN_CENTER);110 cell.setPhrase(new Phrase(value,textfont));111 cell.setBackgroundColor(new BaseColor(255, 255, 255));112 cell.setColspan(4);113 cell.setRowspan(3);114 cell.setFixedHeight(105);115return cell;116 }117118//⽣成表格119public static PdfPTable createTable(int colNumber){120int widths[] = { 35,40,35,35,30 };121 PdfPTable baseTable = new PdfPTable(colNumber);122 baseTable.setWidthPercentage(100);123 baseTable.setSpacingBefore(10);124try {125 baseTable.setWidths(widths);126 } catch (DocumentException e) {127 e.printStackTrace();128 }129return baseTable;130 }131132133public static void addImage(String input,String output,String realPath) throws Exception{134 BufferedOutputStream out = new BufferedOutputStream(135new FileOutputStream(new File(output)));136 PdfReader reader = new PdfReader(input);137 PdfStamper stamper = new PdfStamper(reader, out);138 addWatermark(stamper,"测试添加⽔印⽂字");139int total = reader.getNumberOfPages();140try {141 Image image = Image.getInstance(realPath);142 image.setAbsolutePosition(350, 200);143 image.scaleToFit(160, 70);144 PdfContentByte content= stamper.getOverContent(total);// 在内容上⽅加⽔印145 content.addImage(image);146 }catch (Exception e){147 e.printStackTrace();148 }149150 stamper.close();151 reader.close();152 }153154public static void addWatermark(PdfStamper pdfStamper, String waterMarkName) throws Exception { 155 PdfContentByte content;156 BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",157 BaseFont.NOT_EMBEDDED);158 Rectangle pageRect;159 PdfGState gs = new PdfGState();160try {161if (base == null || pdfStamper == null) {162return;163 }164// 设置透明度为0.4165 gs.setFillOpacity(0.3f);166 gs.setStrokeOpacity(0.3f);167int toPage = pdfStamper.getReader().getNumberOfPages();168for (int i = 1; i <= toPage; i++) {169 pageRect = pdfStamper.getReader().getPageSizeWithRotation(i);170// 计算⽔印X,Y坐标171float x = pageRect.getWidth() / 2;172float y = pageRect.getHeight() / 2;173// 获得PDF最顶层174 content = pdfStamper.getOverContent(i);175 content.saveState();176// set Transparency177 content.setGState(gs);178 content.beginText();179 content.setColorFill(BaseColor.GRAY);180 content.setFontAndSize(base, 30);181// ⽔印⽂字成45度⾓倾斜182 content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, x,183 y, 45);184 content.endText();185 }186 } catch (Exception ex) {187 ex.printStackTrace();188 }189 }190 }4、PDFBuilder类中为设置页⾯附加属性:1package util;23import com.itextpdf.text.*;4import com.itextpdf.text.pdf.*;56import java.io.IOException;78public class PDFBuilder extends PdfPageEventHelper {9/**10 * 页眉11*/12public String header = "";1314/**15 * ⽂档字体⼤⼩,页脚页眉最好和⽂本⼤⼩⼀致16*/17public int presentFontSize = 12;181920// 模板21public PdfTemplate total;2223// 基础字体对象24public BaseFont bf = null;2526// 利⽤基础字体⽣成的字体对象,⼀般⽤于⽣成中⽂⽂字27public Font fontDetail = null;2829/**30 *31 * Creates a new instance of PdfReportM1HeaderFooter ⽆参构造⽅法.32 *33*/34public PDFBuilder() {3536 }3738public void setHeader(String header) {39this.header = header;40 }4142/**43 *44 * TODO ⽂档打开时创建模板45 *46 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(com.itextpdf.text.pdf.PdfWriter,47 * com.itextpdf.text.Document)48*/49public void onOpenDocument(PdfWriter writer, Document document) {50 total = writer.getDirectContent().createTemplate(50, 50);// 共页的矩形的长宽⾼51 }5253/**54 *55 * TODO 关闭每页的时候,写⼊页眉,写⼊'第⼏页共'这⼏个字。
java给图片加水印例子(解决图片出现变红问题)
package image;/*** 图片加水印,在windows正常运行,也可以再Linux上正常运行* 解决图片出现变红问题*/import java.awt.Graphics;import java.awt.GraphicsConfiguration;import java.awt.GraphicsDevice;import java.awt.GraphicsEnvironment;import java.awt.HeadlessException;import java.awt.Image;import java.awt.Toolkit;import java.awt.Transparency;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileOutputStream;import java.io.OutputStream;import javax.imageio.ImageIO;import javax.swing.ImageIcon;public class Image111 {private static int num = 0;private static int num1 = 0;private static int count = 0;public static void main(String[] args) {//目标图片文件夹的路径String srcImgPath = "D:\\image";//水印图片的路径String iconPath = "D:\\mark\\watermark.png";//生成图片文件夹的路径String targerPath = "D:\\image3\\";String os = null;String is = null;File f = new File(srcImgPath);// java.util.List<String> list = getImageUrl(getUrl()); String[] list = f.list();for(String s: list){os = srcImgPath + "\\" + s;for(int i = 0; i < 10; i++){is = targerPath + i + s;markImageByIcon(iconPath, os, is);}// i s = targerPath + s;System.out.println(os);//// markImageByIcon(iconPath, os, is);}System.out.println("本次处理图片: " + num+num1 + " 张"); System.out.println("本次成功处理图片:" + num + " 张"); System.out.println("本次处理图片失败: " + num1 + " 张"); }/*** 给图片添加水印、可设置水印图片旋转角度* @param iconPath 水印图片路径,如果为空,则使用默认水印图片* @param srcImgPath 源图片路径* @param targerPath 目标图片路径*/public static void markImageByIcon(String iconPath, String srcImgPath, String targerPath) {OutputStream os = null;try {Image srcImg =Toolkit.getDefaultToolkit().getImage(srcImgPath);srcImg = new ImageIcon(srcImg).getImage();BufferedImage buffImg = null;GraphicsEnvironment ge =GraphicsEnvironment.getLocalGraphicsEnvironment();try {GraphicsDevice gs = ge.getDefaultScreenDevice();GraphicsConfiguration gc =gs.getDefaultConfiguration();buffImg =gc.createCompatibleImage(srcImg.getWidth(null),srcImg.getHeight(null), Transparency.OPAQUE);} catch (HeadlessException e) {e.printStackTrace();}if (buffImg == null) {buffImg= new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);}Graphics g = buffImg.createGraphics();g.drawImage(srcImg, 0, 0, null);// 得到Image对象。
Java操作图片改变大小加水印
Java操作图片改变大小加水印import java.awt.*;import java.awt.image.*;import javax.imageio.ImageIO;import javax.imageio.ImageIO.*;import javax.imageio.IIOException;import java.io.*;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGImageEncoder;import javax.servlet.http.HttpSession;// 图片操作,改变大小加水印***********@与羊共舞的狼public class ImageOperate {public void waterMark(String strOriginalFileName,String strWaterMarkFileName,HttpSession session){try{//源文件String root=session.getServletContext().getRealPath("/");File fileOriginal = new File(root+strOriginalFileName);Image imageOriginal = ImageIO.read(fileOriginal);int widthOriginal = imageOriginal.getWidth(null);int heightOriginal = imageOriginal.getHeight(null);System.out.println("widthOriginal:" + widthOriginal + "theightOriginal:" + heightOriginal);BufferedImage bufImage = newBufferedImage(widthOriginal,heightOriginal,BufferedImage. TYPE_INT_RGB );Graphics g = bufImage.createGraphics();g.drawImage(imageOriginal,0,0,widthOriginal,heightOrigina l,null);//水印文件File fileWaterMark = new File(root+strWaterMarkFileName);Image imageWaterMark = ImageIO.read(fileWaterMark);int widthWaterMark = imageWaterMark.getWidth(null);int heightWaterMark = imageWaterMark.getHeight(null);System.out.println("widthWaterMark:" + widthWaterMark + "theightWaterMark:" + heightWaterMark);//水印文件在源文件的右下角g.drawImage(imageWaterMark,widthOriginal -widthWaterMark,heightOriginal -heightWaterMark,widthWaterMark,heightWaterMark,null);g.dispose();FileOutputStream fos = new FileOutputStream( root+strOriginalFileName); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos); encoder.encode(bufImage);fos.flush();fos.close();fos = null;}catch(Exception e){e.printStackTrace();}}public void alterSize(String srcImgFile,String addChar,int new_w,int new_h,HttpSession session){//System.out.print("文件路径为:"+"//"+srcImgFile);String root=session.getServletContext().getRealPath("/");java.io.File file=new java.io.File(root+srcImgFile);if(file.exists())System.out.println("文件存在");elseSystem.out.println("文件不存在");int i = srcImgFile.indexOf(".");int sLen = srcImgFile.length();String suffix = srcImgFile.substring(i, sLen); //带点+后缀名String urlName=srcImgFile.substring(0,i); //路径+文件名String newUrlName=root+urlName+addChar+suffix;//System.out.print("新文件名为"+newUrlName);Image src=null;try{src = javax.imageio.ImageIO.read(file);java.awt.image.BufferedImage tag = newjava.awt.image.BufferedImage(new_w,new_h,java.awt.image. BufferedImage .TYPE_INT_RGB);tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); FileOutputStream newimage=new FileOutputStream(newUrlName); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);encoder.encode(tag); //近JPEG编码newimage.close();}catch(IIOException ee){ee.printStackTrace();System.out.print("这里出错了"); }catch(Exception e){e.printStackTrace();}}//End sizeAlter }。
Java添加Word文本水印和图片水印
Java添加Word⽂本⽔印和图⽚⽔印⽔印是⼀种常⽤于各种⽂档的声明、防伪⼿段,⼀般可设置⽂字⽔印或者加载图⽚作为⽔印。
以下内容将分享通过Java编程给Word⽂档添加⽔印效果的⽅法,即⽂本⽔印图⽚⽔印使⽤⼯具:Free Spire.Doc for Java (免费版)Jar导⼊⽅法1:通过官⽹下载控件包。
在程序下新建⼀个directory⽬录,并命名(本⽰例中命名为lib);将控件包lib⽂件夹下的jar(如下图1)复制到程序中新建的⽬录下。
图1:复制jar⽂件后,⿏标右键点击jar⽂件,选择”Add as Library”。
完成导⼊(如下图2)。
图2:引⽤完成后,可以查看包含在其中的类、⽅法、属性等。
如图3:图3:⽅法2:通过maven导⼊。
参考。
Java代码⽰例(供参考)1.添加⽂本⽔印import com.spire.doc.*;import com.spire.doc.documents.WatermarkLayout;import java.awt.*;public class Main {public static void main(String[] args) {//加载测试⽂档Document document = new Document();document.loadFromFile("sample.docx");//插⼊⽂本⽔印InsertTextWatermark(document.getSections().get(0));//保存⽂档document.saveToFile("textwatermark.docx",FileFormat.Docx ); }//⾃定义⽅法指定⽂本⽔印字样,并设置成⽔印private static void InsertTextWatermark(Section section){TextWatermark txtWatermark = new TextWatermark();txtWatermark.setText("内部使⽤");txtWatermark.setFontSize(40);txtWatermark.setColor(Color.red);txtWatermark.setLayout(WatermarkLayout.Diagonal);section.getDocument().setWatermark(txtWatermark);}}⽂本⽔印效果:2. 添加图⽚⽔印import com.spire.doc.*;public class Main {public static void main(String[] args) {//加载测试⽂档Document document = new Document();document.loadFromFile("sample.docx");//加载需要设置成⽔印的图⽚PictureWatermark picture = new PictureWatermark();picture.setPicture("wx.png");picture.setScaling(5);picture.isWashout(false);//将图⽚设置成⽔印document.setWatermark(picture);//保存⽂档document.saveToFile("imagewatermark.docx",FileFormat.Docx );}}图⽚⽔印效果:到此这篇关于Java添加Word⽂本⽔印和图⽚⽔印的⽂章就介绍到这了,更多相关Java添加⽂本⽔印和图⽚⽔印内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。
Java添加水印
Java添加水印(图片水印,文字水印)因为项目中考虑到添加图片版权的保护,特意看了下水印的处理...以下有两种方式: 第一种是添加文字水印:import java.awt.*;import java.awt.image.*;import java.io.*;import javax.swing.*;import com.sun.image.codec.jpeg.*;public class WaterSet {/*** 给图片添加水印** @param filePath* 需要添加水印的图片的路径* @param markContent* 水印的文字* @param markContentColor* 水印文字的颜色* @param qualNum* 图片质量* @return*/public boolean createMark(String filePath, String markContent,Color markContentColor, float qualNum) {ImageIcon imgIcon = new ImageIcon(filePath);Image theImg = imgIcon.getImage();int width = theImg.getWidth(null);int height = theImg.getHeight(null);BufferedImage bimage = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);Graphics2D g = bimage.createGraphics();g.setColor(markContentColor);g.setBackground(Color.white);g.drawImage(theImg, 0, 0, null);g.drawString(markContent, width / 5, height / 5); // 添加水印的文字和设置水印文字出现的内容g.dispose();try {FileOutputStream out = new FileOutputStream(filePath);JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);param.setQuality(qualNum, true);encoder.encode(bimage, param);out.close();} catch (Exception e) {return false;}return true;}}第二种是添加图片水印和文字水印两种方法,水印图片可以是GIF,PNG透明的文件,我一般采用的是PNG的,因为它的质量和GIF相比要高一些:import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Image;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileOutputStream;import javax.imageio.ImageIO;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGImageEncoder;public final class ImageUtils {public ImageUtils() {}/** public final static String getPressImgPath() { return ApplicationContext* .getRealPath("/template/data/util/shuiyin.gif"); }*//*** 把图片印刷到图片上** @param pressImg --* 水印文件* @param targetImg --* 目标文件* @param x* --x坐标* @param y* --y坐标*/public final static void pressImage(String pressImg, String targetImg,int x, int y) {try {//目标文件File _file = new File(targetImg);Image src = ImageIO.read(_file);int wideth = src.getWidth(null);int height = src.getHeight(null);BufferedImage image = new BufferedImage(wideth, height,BufferedImage.TYPE_INT_RGB);Graphics g = image.createGraphics();g.drawImage(src, 0, 0, wideth, height, null);//水印文件File _filebiao = new File(pressImg);Image src_biao = ImageIO.read(_filebiao);int wideth_biao = src_biao.getWidth(null);int height_biao = src_biao.getHeight(null);g.drawImage(src_biao, (wideth - wideth_biao) / 2,(height - height_biao) / 2, wideth_biao, height_biao, null);//水印文件结束g.dispose();FileOutputStream out = new FileOutputStream(targetImg);JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);encoder.encode(image);out.close();} catch (Exception e) {e.printStackTrace();}}/*** 打印文字水印图片** @param pressText* --文字* @param targetImg --* 目标图片* @param fontName --* 字体名* @param fontStyle --* 字体样式* @param color --* 字体颜色* @param fontSize --* 字体大小* @param x --* 偏移量* @param y*/public static void pressText(String pressText, String targetImg,String fontName, int fontStyle, int color, int fontSize, int x,int y) {try {File _file = new File(targetImg);Image src = ImageIO.read(_file);int wideth = src.getWidth(null);int height = src.getHeight(null);BufferedImage image = new BufferedImage(wideth, height,BufferedImage.TYPE_INT_RGB);Graphics g = image.createGraphics();g.drawImage(src, 0, 0, wideth, height, null);// String s="";g.setColor(Color.RED);g.setFont(new Font(fontName, fontStyle, fontSize));g.drawString(pressText, wideth - fontSize - x, height - fontSize/ 2 - y);g.dispose();FileOutputStream out = new FileOutputStream(targetImg);JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);encoder.encode(image);out.close();} catch (Exception e) {System.out.println(e);}}public static void main(String[] args) {pressImage("F:/logo.png", "F:/123.jpg", 0, 0);}}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
图片加水印(java版)一、功能说明1. 将水印图片叠加到原图上2. 可设置水印图片透明度(默认为1 不透明)3. 可设置水印图片相对于原图的左边距和上边距(默认为0)4. 可设置水印图片的宽高(默认为原始尺寸)5. 注意事项. 图片输出到本地. 为防止内存溢出,请增大jvm内存(推荐-Xmx1024m). 可处理20M左右(10000 ×10000)超高清图片二、代码1.原代码import java.awt.AlphaComposite;import java.awt.Graphics2D;import java.awt.Image;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import javax.imageio.stream.ImageInputStream;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGImageEncoder;/*** 图片加水印* <li>图片输出到本地.</li>* <li>为防止内存溢出,请增大jvm内存(推荐<font color='red'>-Xmx1024m</font>).</li> * <li>可处理20M左右大图片.</li>** @author lily200825* @date 2011-6-1*/public class ImageWatermarkUtil {// 输出打印日志public static boolean IS_DEBUG = true;/*** 图片加水印** @param srcImg* 原图片路径* @param watermarkImg* 水印图片路径* @param destImg* 输出图片路径* @param alpha* 水印图透明度* @param left* 水印图相对原图左边距(默认值为<font color='red'>0</font>)* @param top* 水印图相对原图上边距(默认值为<font color='red'>0</font>)* @param width* 水印图输出宽(默认值为<font color='red'>水印图宽</font>)* @param height* 水印图输出高(默认值为<font color='red'>水印图高</font>)* @return* @throws IOException*/public static boolean watermarkImage(String srcImg, String watermarkImg,String destImg, Float alpha, Integer left, Integer top,Integer width, Integer height) throws IOException {if (destImg == null || destImg.trim().length() == 0) {if (IS_DEBUG) {System.err.println("图片加水印:输出图片路径[" + destImg + "]错误。
");}return false;}File srcfile = new File(srcImg);if (srcfile == null || srcfile.exists() == false|| srcfile.isFile() == false) {if (IS_DEBUG) {System.err.println("图片加水印:[" + srcImg + "]文件不存在。
");}return false;}File watermarkfile = new File(watermarkImg);if (watermarkfile == null || watermarkfile.exists() == false|| watermarkfile.isFile() == false) {if (IS_DEBUG) {System.err.println("图片加水印:[" + watermarkImg + "]文件不存在。
");}return false;}return watermarkImage(javax.imageio.ImageIO.read(srcfile),javax.imageio.ImageIO.read(watermarkfile), destImg, alpha,left, top, width, height);}/*** 图片加水印** @param srcInput* 原图输入流* @param watermarkInput* 水印图输入流* @param destImg* 输出图片路径* @param alpha* 水印图透明度* @param left* 水印图相对原图左边距(默认值为<font color='red'>0</font>)* @param top* 水印图相对原图上边距(默认值为<font color='red'>0</font>)* @param width* 水印图输出宽(默认值为<font color='red'>水印图宽</font>)* @param height* 水印图输出高(默认值为<font color='red'>水印图高</font>)* @return* @throws IOException*/public static boolean watermarkImage(InputStream srcInput,InputStream watermarkInput, String destImg, Float alpha,Integer left, Integer top, Integer width, Integer height)throws IOException {if (destImg == null || destImg.trim().length() == 0) {if (IS_DEBUG) {System.err.println("图片加水印:输出图片路径[" + destImg + "]错误。
");}return false;}if (srcInput == null) {if (IS_DEBUG) {System.err.println("图片加水印:源图输入流为空。
");}return false;}if (watermarkInput == null) {if (IS_DEBUG) {System.err.println("图片加水印:水印图输入流为空。
");}return false;}return watermarkImage(javax.imageio.ImageIO.read(srcInput),javax.imageio.ImageIO.read(watermarkInput), destImg, alpha,left, top, width, height);}/*** 图片加水印** @param srcInput* 原图输入流* @param watermarkInput* 水印图输入流* @param destImg* 输出图片路径* @param alpha* 水印图透明度* @param left* 水印图相对原图左边距(默认值为<font color='red'>0</font>)* @param top* 水印图相对原图上边距(默认值为<font color='red'>0</font>)* @param width* 水印图输出宽(默认值为<font color='red'>水印图宽</font>)* @param height* 水印图输出高(默认值为<font color='red'>水印图高</font>)* @return* @throws IOException*/public static boolean watermarkImage(ImageInputStream srcInput,ImageInputStream watermarkInput, String destImg, Float alpha,Integer left, Integer top, Integer width, Integer height)throws IOException {if (destImg == null || destImg.trim().length() == 0) {if (IS_DEBUG) {System.err.println("图片加水印:输出图片路径[" + destImg + "]错误。
");}return false;}if (srcInput == null) {if (IS_DEBUG) {System.err.println("图片加水印:源图输入流为空。
");}return false;}if (watermarkInput == null) {if (IS_DEBUG) {System.err.println("图片加水印:水印图输入流为空。
");}return false;}return watermarkImage(javax.imageio.ImageIO.read(srcInput),javax.imageio.ImageIO.read(watermarkInput), destImg, alpha,left, top, width, height);}public static boolean watermarkImage(Image srcImage, Image watermarkImage,String destImg, Float alpha, Integer left, Integer top,Integer width, Integer height) throws IOException {if (destImg == null || destImg.trim().length() == 0) {if (IS_DEBUG) {System.err.println("图片加水印:输出图片路径[" + destImg + "]错误。