java圖片上傳和加水印


 java圖片上傳和加水印

簡介

    大家在做項目開發的時候,經常會用到圖片上傳,有些牽扯到版權或者私密的圖片需要進行添加上水印,小編在總結了前人的經驗之后,總結了一份element ui+spring boot上傳圖片並加水印的代碼,希望能夠幫助大家,下面廢話就不多說了,開始搞代碼。

java實現圖片上傳

 

  1 Controller代碼                                                          
  2 
  3 @CrossOrigin
  4 
  5 @RestController
  6 
  7 @RequestMapping("/uploadImage")
  8 
  9 public class UploadController {
 10 
 11  
 12 
 13     @RequestMapping(value = "/uplaod", method = {RequestMethod.GET, RequestMethod.POST})
 14 
 15     @ResponseBody
 16 
 17     public HashMap<String, Object> uplaod(HttpServletRequest request, @RequestParam("img") MultipartFile file, @RequestParam("type") String type) {
 18 
 19  
 20 
 21         HashMap<String, Object> result = new HashMap<String, Object>();
 22 
 23         //想要存儲文件的地址
 24 
 25         String pathName = "upload/";
 26 
 27         // 定義文件全路徑
 28 
 29         String pathFullName="";
 30 
 31         File filePath = new File(pathName);
 32 
 33         // 判斷目錄是否存在,如果不存在,創建文件目錄
 34 
 35         if (!filePath.exists() && !filePath.isDirectory()) {
 36 
 37             System.out.println("目錄不存在,創建目錄:" + filePath);
 38 
 39             filePath.mkdirs();
 40 
 41         }
 42 
 43         // 定義一個uuid用來保存圖片的名字,也可以根據自己的需求來定義保存文件的名字
 44 
 45         UUID uuid = UUID.randomUUID();
 46 
 47         //獲取文件名(包括后綴)
 48 
 49         String uploadName = file.getOriginalFilename();
 50 
 51         // 取得文件名后綴
 52 
 53         String suffix = uploadName.substring(uploadName.lastIndexOf(".") + 1);
 54 
 55  
 56 
 57         pathFullName = pathName + uuid.toString() + "." + suffix;
 58 
 59  
 60 
 61         SysDict sysDict = new SysDict();
 62 
 63         sysDict.setDictCode(type);
 64 
 65         SysDict resDict = sysDictService.getSysDict(sysDict);
 66 
 67         FileOutputStream fos = null;
 68 
 69         try {
 70 
 71             fos = new FileOutputStream(pathFullName);
 72 
 73             fos.write(file.getBytes()); // 寫入文件
 74 
 75  
 76 
 77             // 添加水印
 78 
 79             String srcImgPath = pathFullName; //源圖片地址
 80 
 81             String tarImgPath = pathFullName; //待存儲的地址
 82 
 83             //格式化時間
 84 
 85             SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 86 
 87             String format = f.format(new Date());
 88 
 89             String waterMarkContent = "要添加的水印內容";  //水印內容
 90 
 91  
 92 
 93             WaterMarkUtil.markImage(waterMarkContent, pathName, tarImgPath);
 94 
 95  
 96 
 97             //System.out.println("文件上傳成功");
 98 
 99             HashMap<String, String> data = new HashMap<String, String>();
100 
101             result.put("code", "200");
102 
103             data.put("url", apiUrl + pathName);
104 
105             result.put("data", data);
106 
107             return result;
108 
109         } catch (Exception e) {
110 
111             e.printStackTrace();
112 
113             result.put("code", "0");
114 
115             return result;
116 
117         } finally {
118 
119             try {
120 
121                 fos.close();
122 
123             } catch (IOException e) {
124 
125                 e.printStackTrace();
126 
127             }
128 
129         }
130 
131     }
132 
133 }

 

02java添加水印

創建WaterMarkUtil.java的工具類,添加水印用

  1 package com.ten.ms.tmsframework.common.Util;
  2 
  3  
  4 
  5  
  6 
  7 import java.awt.AlphaComposite;
  8 
  9 import java.awt.Color;
 10 
 11 import java.awt.Font;
 12 
 13 import java.awt.Graphics2D;
 14 
 15 import java.awt.Image;
 16 
 17 import java.awt.RenderingHints;
 18 
 19 import java.awt.image.BufferedImage;
 20 
 21 import java.io.File;
 22 
 23 import java.io.FileOutputStream;
 24 
 25 import java.io.InputStream;
 26 
 27 import java.io.OutputStream;
 28 
 29 import javax.imageio.ImageIO;
 30 
 31  
 32 
 33 public class WaterMarkUtil {
 34 
 35     // 水印透明度
 36 
 37     private static float alpha = 0.3f;
 38 
 39     // 水印橫向位置
 40 
 41     private static int positionWidth = 50;
 42 
 43     // 水印縱向位置
 44 
 45     private static int positionHeight = 100;
 46 
 47     // 水印文字字體
 48 
 49     private static Font font = new Font("宋體", Font.BOLD, 60);
 50 
 51     // 水印文字顏色
 52 
 53     private static Color color = Color.red;
 54 
 55  
 56 
 57     /**
 58 
 59      * 給圖片添加水印文字
 60 
 61      *
 62 
 63      * @param text       水印文字
 64 
 65      * @param srcImgPath 源圖片路徑
 66 
 67      * @param targetPath 目標圖片路徑
 68 
 69      */
 70 
 71     public static void markImage(String text, String srcImgPath, String targetPath) {
 72 
 73         markImage(text, srcImgPath, targetPath, null);
 74 
 75     }
 76 
 77  
 78 
 79     /**
 80 
 81      * 給圖片添加水印文字、可設置水印文字的旋轉角度
 82 
 83      *
 84 
 85      * @param text 水印文字
 86 
 87      * @param srcImgPath 源圖片路徑
 88 
 89      * @param targetPath 目標圖片路徑
 90 
 91      * @param degree 水印旋轉
 92 
 93      */
 94 
 95     public static void markImage(String text, String srcImgPath, String targetPath, Integer degree) {
 96 
 97  
 98 
 99         OutputStream os = null;
100 
101         try {
102 
103             // 0、圖片類型
104 
105             String type = srcImgPath.substring(srcImgPath.indexOf(".") + 1, srcImgPath.length());
106 
107  
108 
109             // 1、源圖片
110 
111             Image srcImg = ImageIO.read(new File(srcImgPath));
112 
113  
114 
115             int imgWidth = srcImg.getWidth(null);
116 
117             int imgHeight = srcImg.getHeight(null);
118 
119  
120 
121             BufferedImage buffImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
122 
123  
124 
125             // 2、得到畫筆對象
126 
127             Graphics2D g = buffImg.createGraphics();
128 
129             // 3、設置對線段的鋸齒狀邊緣處理
130 
131             g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
132 
133             g.drawImage(srcImg.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH), 0, 0, null);
134 
135             // 4、設置水印旋轉
136 
137             if (null != degree) {
138 
139                 g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
140 
141             }
142 
143             // 5、設置水印文字顏色
144 
145             g.setColor(color);
146 
147             // 6、設置水印文字Font
148 
149             g.setFont(font);
150 
151             // 7、設置水印文字透明度
152 
153             g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
154 
155             // 8、第一參數->設置的內容,后面兩個參數->文字在圖片上的坐標位置(x,y)
156 
157  
158 
159             //設置水印的坐標
160 
161             int x = imgWidth - 2*getWatermarkLength(text, g);
162 
163             int y = imgHeight - 2*getWatermarkLength(text, g);
164 
165             g.drawString(text, x, y);  //畫出水印
166 
167 //            g.drawString(text, positionWidth, positionHeight);
168 
169             // 9、釋放資源
170 
171             g.dispose();
172 
173             // 10、生成圖片
174 
175             os = new FileOutputStream(targetPath);
176 
177             // ImageIO.write(buffImg, "JPG", os);
178 
179             ImageIO.write(buffImg, type.toUpperCase(), os);
180 
181  
182 
183         } catch (Exception e) {
184 
185             e.printStackTrace();
186 
187         } finally {
188 
189             try {
190 
191                 if (null != os)
192 
193                     os.close();
194 
195             } catch (Exception e) {
196 
197                 e.printStackTrace();
198 
199             }
200 
201         }
202 
203     }
204 
205  
206 
207     /**
208 
209      * 給圖片添加水印文字、可設置水印文字的旋轉角度
210 
211      * @param text 水印文字
212 
213      * @param inputStream 源圖片路徑
214 
215      * @param outputStream 目標圖片路徑
216 
217      * @param degree 水印旋轉
218 
219      * @param typeName
220 
221      */
222 
223     public static void markImageByIO(String text, InputStream inputStream, OutputStream outputStream,
224 
225                                      Integer degree, String typeName) {
226 
227         try {
228 
229             // 1、源圖片
230 
231             Image srcImg = ImageIO.read(inputStream);
232 
233  
234 
235             int imgWidth = srcImg.getWidth(null);
236 
237             int imgHeight = srcImg.getHeight(null);
238 
239             BufferedImage buffImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
240 
241  
242 
243             // 2、得到畫筆對象
244 
245             Graphics2D g = buffImg.createGraphics();
246 
247             // 3、設置對線段的鋸齒狀邊緣處理
248 
249             g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
250 
251             g.drawImage(srcImg.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH), 0, 0, null);
252 
253             // 4、設置水印旋轉
254 
255             if (null != degree) {
256 
257                 g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
258 
259             }
260 
261             // 5、設置水印文字顏色
262 
263             g.setColor(color);
264 
265             // 6、設置水印文字Font
266 
267             g.setFont(font);
268 
269             // 7、設置水印文字透明度
270 
271             g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
272 
273             // 8、第一參數->設置的內容,后面兩個參數->文字在圖片上的坐標位置(x,y)
274 
275  
276 
277             g.drawString(text, positionWidth, positionHeight);
278 
279             // 9、釋放資源
280 
281             g.dispose();
282 
283             // 10、生成圖片
284 
285             ImageIO.write(buffImg, typeName.toUpperCase(), outputStream);
286 
287  
288 
289         } catch (Exception e) {
290 
291             e.printStackTrace();
292 
293         }
294 
295     }
296 
297  
298 
299     public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
300 
301         return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
302 
303     }
304 
305 }

 

03element ui前台html代碼

<el-upload class="text_uploader" 

 :show-file-list="false" 

 :before-upload="beforeUpload" // 上傳之前執行的方法

 :on-success="onSuccess" //成功后執行的方法

 :on-error="onError" 

 :action="后台url地址">

 

<el-button :disabled="importDataDisabled" type="success" :icon="importDataBtnIcon">

按鈕

</el-button>

</el-upload>

 

    java的上傳圖片和加水印基本上使用這些就可以了,大家也可以把加水印和圖片上傳抽成一個共同的方法方便以后開發項目的時候繼續使用。后續我會分享更多的技術相關的內容,請大家多多關注。

 

關注我發現更多精彩

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM