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的上传图片和加水印基本上使用这些就可以了,大家也可以把加水印和图片上传抽成一个共同的方法方便以后开发项目的时候继续使用。后续我会分享更多的技术相关的内容,请大家多多关注。
关注我发现更多精彩