本博客介紹一下用jdk awt實現圖片加文字水印和圖片水印的方法java
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 java.io.FileOutputStream; import java.io.OutputStream; import javax.imageio.ImageIO; import javax.swing.ImageIcon; public class WaterMarkIMGUtils { /** * @param args */ public static void main(String[] args) { String srcImgPath = "C:/Users/zhaoh/Desktop/test.jpg"; String targerPath1 = "C:/Users/zhaoh/Desktop/target1.jpg"; WaterMarkIMGUtils.setWaterMarkForIMGByFontString(srcImgPath, targerPath1, Color.blue, "公司內部資料"); } public static void setWaterMarkForIMGByFontString(String srcImgPath, String targerPath, Color markContentColor, String waterMarkContent){ OutputStream os = null; try { Image srcImg = ImageIO.read(new File(srcImgPath)); 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); Font font = new Font("宋體", Font.PLAIN, 20); g.setColor(markContentColor); // 根據圖片的背景設置水印顏色 g.setFont(font); int srcImgWidth = srcImg.getWidth(null); int srcImgHeight = srcImg.getHeight(null); int waterMarkLength = g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length()); int x = srcImgWidth - waterMarkLength - 3; int y = srcImgHeight - 3; g.drawString(waterMarkContent, x, y); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); g.dispose(); os = new FileOutputStream(targerPath); // 生成圖片 ImageIO.write(buffImg, "JPG", os); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != os) os.close(); } catch (Exception e) { e.printStackTrace(); } } } }
原來圖片 app
加上文字水印後圖片 maven
import java.awt.AlphaComposite; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; 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 WaterMarkIMGUtils { /** * 給圖片添加水印 * @param iconPath * 水印圖片路徑 * @param srcImgPath * 源圖片路徑 * @param targerPath * 目標圖片路徑 * @param imgType * 上傳附件的類型 */ public static void setWaterMarkForIMGByIcon(BufferedImage bufferedImage, InputStream in, OutputStream os, String imgType) { setWaterMarkForIMG(iconPath, srcImgPath, targerPath, null, imgType); } /** * 給圖片添加水印 * @date 2019年6月12日下午2:11:11 * @param iconPath * 水印圖片路徑 * @param srcImgPath * 源圖片路徑 * @param targerPath * 目標圖片路徑 * @param degree * 選擇角度 * @param imgType * 上傳附件的類型 */ public static void setWaterMarkForIMGByIcon(String iconPath, String srcImgPath, String targerPath, Integer degree,String imgType) { OutputStream os = null; try { Image srcImg = ImageIO.read(new File(srcImgPath)); 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); } // 水印圖象的路徑 水印通常爲gif或者png的,這樣可設置透明度 ImageIcon imgIcon = new ImageIcon(iconPath); // 獲得Image對象。 Image img = imgIcon.getImage(); float alpha = 0.5f; // 透明度 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); // 表示水印圖片的位置 g.drawImage(img, 150, 300, null); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); g.dispose(); os = new FileOutputStream(targerPath); // 生成圖片 ImageIO.write(buffImg, imgType, os); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != os) os.close(); } catch (Exception e) { e.printStackTrace(); } } } public static void main(String[] args) { String srcImgPath = "C:/Users/admin/Desktop/test.jpg"; String iconPath = "C:/Users/admin/Desktop/logo.png"; String targerPath1 = "C:/Users/admin/Desktop/target1.jpg"; String targerPath2 = "C:/Users/admin/Desktop/target2.jpg"; // 給圖片添加水印 WaterMarkIMGUtils.setWaterMarkForIMGByIcon(iconPath, srcImgPath, targerPath1,"JPG"); // 給圖片添加水印,水印旋轉-10 WaterMarkIMGUtils.setWaterMarkForIMGByIcon(iconPath, srcImgPath, targerPath2, -10,"JPG"); } }
原來圖片: 工具
水印圖片: 添加水印後的圖片: google
【拓展功能】 上面代碼參考網上教程,不少地方都有分享代碼,而後下面對其進行拓展url
業務場景,基於圖片加圖片水印的功能,如今要求上傳圖片時候就給加上二維碼,用戶能夠掃描二維碼獲取對應數據spa
首先二維碼裏面其實也就是一些數據,好比一個連接,或者一堆文字等等,這裏能夠經過Google開源的zxing庫來事項生成二維碼圖片,而後附加到圖片,造成水印excel
maven配置zxing對應jar:code
<!-- 條形碼、二維碼生成 --> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>2.2</version> </dependency>
寫個工具類用於生成二維碼圖片:orm
import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Hashtable; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; /** * 二維碼生成工具類 */ public class QrCodeUtils { /** * 生成二維碼 * @author nicky.ma * @date 2019年6月11日下午4:39:16 * @param contents 二維碼的內容 * @param width 二維碼圖片寬度 * @param height 二維碼圖片高度 */ public static BufferedImage createQrCodeBufferdImage(String contents, int width, int height){ Hashtable hints= new Hashtable(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); BufferedImage image = null; try { BitMatrix bitMatrix = new MultiFormatWriter().encode( contents,BarcodeFormat.QR_CODE, width, height, hints); image = toBufferedImage(bitMatrix); } catch (WriterException e) { e.printStackTrace(); } return image; } public static BufferedImage toBufferedImage(BitMatrix matrix) { int width = matrix.getWidth(); int height = matrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); } } return image; } }
寫個圖片添加圖片水印的工具類,代碼僅供參考 注意:二維碼要清晰度要求比較高,就不要設置透明效果了
import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import com.itextpdf.text.BadElementException; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfGState; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; import com.itextpdf.text.pdf.PdfStructTreeController.returnType; import com.itextpdf.text.pdf.parser.PdfImageObject.ImageBytesType; import com.stuff.stuffmanage.model.CommonStuffModel; /** * * <pre> * 水印處理工具類. <br> * </pre> * * @author nicky.ma * @date 2019/06/11 */ public class WaterMarkUtils { /** * 生成二維碼 * @author nicky.ma * @date 2019年6月12日下午2:15:51 * @param commonStuffModel * @return */ private static BufferedImage createQrCodeImg(CommonStuffModel commonStuffModel){ StringBuffer strBuf = new StringBuffer(); strBuf.append("材料入庫時間:").append(new SimpleDateFormat("yyyy-MM-dd").format(new Date())).append("\n"); strBuf.append("材料有效期:").append(commonStuffModel.getValidEndDateStr()).append("\n"); strBuf.append("材料名稱:").append(commonStuffModel.getStuffName()).append("\n"); strBuf.append("材料目錄:").append(commonStuffModel.getDirName()).append("\n"); strBuf.append("材料版本:").append(commonStuffModel.getVersion()).append("\n"); strBuf.append("出具單位:").append(commonStuffModel.getIssueUnit()).append("\n"); // 生成二維碼 BufferedImage bufferedImage = QrCodeUtils.createQrCodeBufferdImage(strBuf.toString(), 175, 175); return bufferedImage; } /** * 圖片附件添加二維碼水印 * @author nicky.ma * @date 2019年6月12日下午2:13:29 * @param bos * 文件保存 IO stream * @param input * 獲取文件上傳IO stream * @param commonStuffModel * 公共材料庫信息實體 * @param imgType * 附件類型 */ public static void setQrCodeForIMG(BufferedOutputStream bos, InputStream input, ApprCommonStuffModel apprCommonStuffModel, String imgType){ BufferedImage bufferedImage = createQrCodeImg(apprCommonStuffModel); //圖片附件加上二維碼水印 setWaterMarkForIMG(bufferedImage, input, bos, imgType); } /** * 給圖片添加水印 * @param bufferedImage * 水印圖片 * @param in * 獲取附件上傳stream * @param os * 附件保存stream * @param imgType * 上傳附件的類型 */ public static void setWaterMarkForIMG(BufferedImage bufferedImage, InputStream in, OutputStream os, String imgType) { setWaterMarkForIMG(bufferedImage, in, os, null, imgType); } /** * 給圖片添加水印、可設置水印圖片旋轉角度 * @author nicky.ma * @date 2019年6月12日下午2:11:11 * @param bufferedImage * 水印圖片 * @param in * 獲取附件上傳stream * @param os * 附件保存stream * @param degree * 選擇角度 * @param imgType * 上傳附件的類型 */ public static void setWaterMarkForIMG(BufferedImage bufferedImage, InputStream in, OutputStream os, Integer degree,String imgType) { //OutputStream os = null; long startTime = System.currentTimeMillis(); System.out.println("圖片附件添加圖片水印 start"); try { Image srcImg = ImageIO.read(in); 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); } //float alpha = 0.2f; // 透明度 //g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); // 水印圖象的路徑 水印通常爲gif或者png的,這樣可設置透明度 //ImageIcon imgIcon = new ImageIcon(iconPath); // 獲得Image對象。 //Image img = imgIcon.getImage(); // 表示水印圖片的位置 g.drawImage(bufferedImage, buffImg.getWidth()-180, 0, null); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); g.dispose(); //os = new FileOutputStream(targerPath); // 生成圖片 ImageIO.write(buffImg, imgType, os); long endTime = System.currentTimeMillis(); System.out.println("圖片附件添加圖片水印 ok 所用時間:"+(endTime-startTime)+"s"); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != os) os.close(); } catch (Exception e) { e.printStackTrace(); } } } }
對於上傳的文件,咱們怎麼知道類型?若是用Spring提供的MultipartFile,這裏能夠獲取ContentType來判斷,這裏只提供思路
/**文件類型集合*/ private static Map<String,String> FILE_TYPES =new HashMap<String,String>(); /**圖片類型集合*/ private static Map<String,String> IMG_TYPES = new HashMap<String,String>(); static{ FILE_TYPES.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//xlsx FILE_TYPES.put("xls", "application/vnd.ms-excel");//xls FILE_TYPES.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");//docx FILE_TYPES.put("doc", "application/msword");//doc FILE_TYPES.put("jpg", "image/jpeg");//jpg FILE_TYPES.put("png", "image/png");//png FILE_TYPES.put("gif", "image/gif");//gif FILE_TYPES.put("bmp", "image/bmp");//bmp FILE_TYPES.put("txt", "text/plain");//txt FILE_TYPES.put("pdf", "application/pdf");//pdf FILE_TYPES.put("zip", "application/x-zip-compressed");//zip FILE_TYPES.put("rar", "application/octet-stream");//rar } static{ IMG_TYPES.put("jpg", "image/jpeg");//jpg IMG_TYPES.put("png", "image/png");//png IMG_TYPES.put("gif", "image/gif");//gif IMG_TYPES.put("bmp", "image/bmp");//bmp } /** * 校驗上傳附件是否爲圖片類型的 * @author nicky.ma * @date 2019年6月12日上午11:15:30 * @param fileContentType * response格式ContentType */ public static boolean checkContainImgType(String fileContentType){ if(!StringUtils.isEmpty(fileContentType)){ return IMG_TYPES.containsValue(fileContentType); } return false; } public static String loadFileType(String fileContentType){ for(Map.Entry<String, String> entry : FILE_TYPES.entrySet()){ if(entry.getValue().equals(fileContentType)){ return entry.getKey(); } } return null; }
有了工具類以後,咱們須要獲取文件上傳的inputStream
public void upload(MultipartFile myfiles,String url,String rootPath,CommonStuffModel commonStuffModel)throws Exception{ if(!myfiles.isEmpty()){ File localFile = new File(rootPath+url); File parentFile = localFile.getParentFile(); if(!parentFile.exists()){ parentFile.mkdirs(); } String contentType = myfiles.getContentType(); if(checkContainImgType(contentType)){//上傳了圖片類型附件 InputStream inputStream = myfiles.getInputStream(); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(localFile)); WaterMarkUtils.setQrCodeForIMG(bos, inputStream, commonStuffModel,CommonFileUtil.loadFileType(contentType)); }else{ myfiles.transferTo(localFile); } } }
ok,生成二維碼水印