png/jpg/pdf文件上传时添加水印
最近在公司遇到了一个还算是比较复杂的业务吧,因为这个业务是给png格式;jpg格式;还有pdf格式的文件添加水印,其实图片格式的文件用java做水印还是比较好做的,但是pdf的做起来很麻烦为了做这个业务也是呕心沥血啊,好了我们直接看代码吧.
png/jpg加图片水印
首先我们得判断文件格式这边是我自己写的一个判断图片格式的util 希望各位能够采纳
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtils {
private final static String reg = ".+(.JPEG|.jpg|.jpeg|.JPG|.png|.PNG)$";
private final static String PDF = ".+(.PDF|.pdf)$";
public static boolean isImg (String fileName){
boolean isNull = nonEmpty(fileName);
if (isNull) {
Matcher matcher = Pattern.compile(reg).matcher(fileName);
if (!matcher.find()) {
return false;
}
return true;
}
return false;
}
public static boolean pdf (String fileName){
boolean isNull = nonEmpty(fileName);
if (isNull) {
Matcher matcher = Pattern.compile(PDF).matcher(fileName);
if (!matcher.find()) {
return false;
}
return true;
}
return false;
}
private static boolean nonEmpty(String str){
if (null == str || "".equals(str) || str.length() == 0){
return false;
}
return true;
}
}
下面是给png/jpg加水印,当然了这个导入和导出都是MultipartFile,如果有其他需求可以自己自定义
private static int positionWidth;
private static int positionHeight;
public static MultipartFile markImageByIcon(String iconPath, MultipartFile srcFile, Integer degree) {
InputStream is = null;
OutputStream os = null;
try {
InputStream inputImg = srcFile.getInputStream();
Image srcImg = ImageIO.read(inputImg);
BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null),
BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);
if (null != degree) {
g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
}
ImageIcon imgIcon = new ImageIcon(iconPath);
Image img = imgIcon.getImage();
positionWidth = Math.max(srcImg.getWidth(null) - imgIcon.getIconWidth(), 0);
positionHeight = Math.max(srcImg.getHeight(null) - imgIcon.getIconHeight(), 0);
g.drawImage(img, positionWidth, positionHeight, null);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
g.dispose();
String originFileName = srcFile.getOriginalFilename();
int lastSplit = originFileName.lastIndexOf(".");
String suffix = originFileName.substring(lastSplit + 1);
String dOriginFileName = srcFile.getOriginalFilename();
String dContentType = srcFile.getContentType();
ByteArrayOutputStream bs = new ByteArrayOutputStream();
ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
ImageIO.write(buffImg, suffix, imOut);
is = new ByteArrayInputStream(bs.toByteArray());
srcFile = new MockMultipartFile(dOriginFileName, dOriginFileName, dContentType,
is);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != is)
is.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (null != os)
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return srcFile;
}
下面是pdf加水印
首先这个比较复杂,因为这个是文件的格式,而且要加水印给每页都得加,就得得到总页数,所需我们需要用到一个工具jar “aspose” 在你的pom文件中引入下面这个坐标
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-pdf<artifactI>
<version>17.3.0</version>
</dependency>
然后再将jar包放到你的本地磁盘下,随便一个目录jar在最后
然后执行这个命令,当然了一定要配置mvn命令,没有配置maven环境变量的同学可以自己配置下 注: “F:\jars_aaa” 可以改成自己的磁盘位置
mvn install:install-file -Dfile="F:\jars_aaa\aspose.pdf-17.3.0.jar" -DgroupId=com.aspose -DartifactId=aspose-pdf -Dversion=17.3.0 -Dpackaging=jar
然后就可以开心的敲代码,我这边传入的文件和return的文件都是MultipartFile类型,你们可以自己更改
private static String CACHE_PATH = "E:/cache/";
public static MultipartFile addWatermark(MultipartFile srcPdf,String path){
byte [] byteArr= new byte[0];
try {
byteArr = srcPdf.getBytes();
InputStream inputStream = new ByteArrayInputStream(byteArr);
Document pdfDocument = new Document(inputStream);
ImageStamp imageStamp = new ImageStamp(path);
imageStamp.setHeight(60);
imageStamp.setWidth(120);
imageStamp.setOpacity(0.5);
imageStamp.setXIndent(470.0F);
PageCollection pages = pdfDocument.getPages();
int size = pages.size();
for (int i = 1; i <= size; i++) {
imageStamp.setRightMargin(-100.0F);
pages.get_Item(i).addStamp(imageStamp);
}
pdfDocument.save(CACHE_PATH + srcPdf.getOriginalFilename());
srcPdf = fileToMultipart(CACHE_PATH + srcPdf.getOriginalFilename());
} catch (IOException e) {
e.printStackTrace();
}
return srcPdf;
}
public static MultipartFile fileToMultipart(String path){
File file = new File(path);
FileItemFactory factory = new DiskFileItemFactory();
FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
int bytesRead;
byte[] buffer = new byte[LENGTH];
try (FileInputStream fis = new FileInputStream(file);
OutputStream os = item.getOutputStream()) {
while ((bytesRead = fis.read(buffer, 0, LENGTH)) != -1) {
os.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
System.out.println("文件转化失败, fileUrl: "+ file.getName());
System.out.println("e: "+e);
return null;
}finally {
file.delete();
}
return new CommonsMultipartFile(item);
}
再给大家贴一下import吧
import com.aspose.pdf.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.*;
import java.awt.*;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import static org.apache.poi.hpsf.ClassID.LENGTH;
好了今天就到这儿,如果需要jar可直接私信
|