话不多说直接上代码: 这里面有个坑,就是苹果手机的图片有些传输到后台的并不是以图片格式为后缀的图片文件,直接是个file(没有后缀...),所以需要进行处理
//#加水印时的图片路径,本地用D:/ //#线上用服务器的路径 //#uploadPath: D:/ //#uploadPath: /usr/local/nginx/html/service-work/download/ @Value("${server.uploadPath}") private String uploadPath; //将附件uploadPath上传至阿里云OOS uploadOldName: http://localhost:8089/file/upload/oldName
@Value("${file.uploadOldName}") private String uploadOldName;
//视图层的内容 /** * 考勤打卡照片加水印并上传 */ @PostMapping("/appPhotoUpload") @ApiOperation(value = ApiConstant.WORK_APP_UPLOAD_API, tags = ApiConstant.WORK_APP_API,response = String.class) public ResponseEntity appPhotoUpload(@RequestParam("file") MultipartFile files,@RequestParam("addRess") String addRess,HttpServletRequest request) throws IOException { try { log.info("图片大小: {} kb",files.getBytes().length / 1024); //System.out.println(); } catch (IOException e) { e.printStackTrace(); } // 当前日期 SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm"); String time = sdf.format(new Date()); // 周几 SimpleDateFormat dateFm = new SimpleDateFormat("EEEE", Locale.CHINA); String address = addRess; String param = URLDecoder.decode(address, "utf-8"); String text = time+" "+dateFm.format(new Date())+param;//水印内容 File file = convert(files,request); boolean flag = isIOS(request); String fileName = appService.addTextToImage(file,text,new Color(231, 65, 51),request,flag); return ok(fileName); }
public File convert(MultipartFile file,HttpServletRequest request) throws IOException { boolean flag = isIOS(request); log.info("是否是苹果手机==={}",flag); //true代表是ios File convFile; String fileType = FileTypeUtil.getType(file.getInputStream()); log.info("当前文件的后缀名==={}",fileType); if(flag){ String suffix = null; suffix = ".jpg"; String newFileName = uploadPath + "temporary" + suffix; convFile = new File(newFileName); //file.transferTo(convFile); }else{ String suffix = null; suffix = ".jpg"; String newFileName = uploadPath + "temporary" + suffix; convFile = new File(newFileName); //convFile = new File(file.getOriginalFilename()); } convFile.createNewFile(); FileOutputStream fos = new FileOutputStream(convFile); fos.write(file.getBytes()); fos.close(); return convFile; }
//业务层的内容
/* * 加文字水印并换行 * @param file * @param text * @param color * @throws IOException */ public String addTextToImage(File file, String text, Color color,HttpServletRequest request,boolean flag) throws IOException { log.info("---图片加文字水印并换行---"); //压缩后的图片路径 String saveFilePath = uploadPath+"compress.jpg"; Image image = ImageIO.read(file); int imgWidth = image.getWidth(null); int imgHeight = image.getHeight(null); compressImage(file.getAbsolutePath(), saveFilePath, 640,((640*imgHeight)/imgWidth)); // 缩略图 File srcImgFile = new File(saveFilePath); log.info("文件信息===={}",srcImgFile.getAbsolutePath()); log.info("文件信息2===={}",srcImgFile.getPath()); Image srcImg = ImageIO.read(srcImgFile); int srcImgWidth = srcImg.getWidth(null); int srcImgHeight = srcImg.getHeight(null); //log.info("====新====srcImgWidth====="+srcImgWidth); //log.info("====新====imgHeight======="+imgHeight); BufferedImage bi = new BufferedImage(srcImgWidth,srcImgHeight,BufferedImage.TYPE_INT_ARGB); float alpha = 1F; Graphics2D g = bi.createGraphics(); //高清代码 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha); g.setComposite(ac); g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null); g.setColor(color); g.setBackground(Color.BLACK); Font font = new Font("微软雅黑",Font.PLAIN,30); g.setFont(font); FontRenderContext frc = g.getFontRenderContext(); //文字叠加,自动换行叠加 int fontSize = font.getSize(); int tempX = srcImgWidth - (srcImgWidth - 100);// 水印位置坐标 int tempY = srcImgHeight - (srcImgHeight - 100);// 水印位置坐标 int tempCharLen = 0;//单字符长度 int tempLineLen = 0;//单行字符总长度临时计算 StringBuffer sb =new StringBuffer(); int length = 0; log.info("=====要写入的水印文字======"+text); for(int i=0; i<text.length(); i++) { char tempChar = text.charAt(i); tempCharLen = getCharLen(tempChar, g); tempLineLen += tempCharLen; if(tempLineLen >= 370) { length = length+1; TextLayout tl = new TextLayout(sb.toString(), font, frc); Shape sha = tl.getOutline(AffineTransform.getTranslateInstance(tempX,tempY)); //长度已经满一行,进行文字叠加 //描边色 g.setColor(Color.black); g.draw(sha); //字体色 g.setColor(Color.white); g.fill(sha); log.info("=====第一行水印文字======"+sb); sb.delete(0, sb.length());//清空内容,重新追加 tempY += fontSize; tempLineLen =0; } sb.append(tempChar);//追加字符 } log.info("=====换行水印文字======"+sb); TextLayout tl = new TextLayout(sb.toString(), font, frc); Shape sha = tl.getOutline(AffineTransform.getTranslateInstance(tempX,tempY)); //描边色 g.setColor(Color.black); g.draw(sha); //字体色 g.setColor(Color.white); g.fill(sha); // 输出图片 FileOutputStream outImgStream = new FileOutputStream(file); ImageIO.write(bi, "PNG", outImgStream); log.info("=====添加水印完成======"); outImgStream.flush(); outImgStream.close(); //File files = file; log.info("=====上传文件名======"+file.getName()); String newFileName = null; String newFileNames = null; String name = null; String suffix = null; File newFiles = null; try { newFileName = uploadFileOrg(file); // if(null != file){ // Boolean isoFlag = file.delete(); // log.info("---原图片---是否删除---"+isoFlag); // } if(null != srcImgFile){ Boolean isoFlag = srcImgFile.delete(); log.info("---缩略图---是否删除---"+isoFlag); } }catch (Exception e) { e.printStackTrace(); } return newFileName; }
/** * * 将图片按照指定的图片尺寸压缩 * @param srcImgPath :源图片路径 * @param outImgPath :输出的压缩图片的路径 * @param new_w :压缩后的图片宽 * @param new_h :压缩后的图片高 */ public static void compressImage(String srcImgPath, String outImgPath, int new_w, int new_h) { BufferedImage src = InputImage(srcImgPath); disposeImage(src, outImgPath, new_w, new_h); }
//调用上传图片url将图片传输到阿里云OSS
public String uploadFileOrg(File file){ CloseableHttpClient httpclient = HttpClients.createDefault(); String fileName = null; long stateTime = System.currentTimeMillis(); log.info("开始调用org工程图片上传,当前系统时间==={}",stateTime); // 调用org上传图片方法 try { HttpPost httppost = new HttpPost(uploadOldName); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000) .setSocketTimeout(200000).build(); httppost.setConfig(requestConfig); System.out.println(file.getAbsolutePath()); FileBody bin = new FileBody(file); System.out.println(bin.getFilename()); StringBody comment = new StringBody("This is comment", ContentType.TEXT_PLAIN); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", bin).addPart("comment", comment).build(); httppost.setEntity(reqEntity); httppost.setHeader("appKey","kq"); httppost.setHeader("Authorization","service-work"); //System.out.println("--上传地址--" + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { //System.out.println("--上传返回的状态值--"+response.getStatusLine()); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { log.info("调用org工程图片上传成功,当前系统时间==={},总耗时==={}",System.currentTimeMillis(),System.currentTimeMillis()-stateTime); String responseEntityStr = EntityUtils.toString(response.getEntity()); fileName = responseEntityStr; System.out.println("--上传返回信息--"+responseEntityStr); }else{ throw new AppBusinessException(UserErrorCode.UPLOAD_ERROR); } EntityUtils.consume(resEntity); } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } String newFileName =""; try { if(null == fileName){ throw new AppBusinessException(UserErrorCode.UPLOAD_ERROR); }else{ JSONObject jsonObject = JSONObject.parseObject(fileName); newFileName=jsonObject.getString("newFileName"); } }finally { // 不管上传是否成功删除写入水印的图片 if(file != null ){ Boolean deleteFlag = file.delete(); System.out.println("------file是否删除了----"+deleteFlag); } } return newFileName; }
//此处是将文件上传到阿里云OSS的代码
@AuthToken @PostMapping({"/upload/oldName"}) @ApiOperation(value = ApiConstant.FILE_UPLOAD_OLDNAME_API, tags = {ApiConstant.FILE_API}) public ResponseEntity uploadName(@RequestParam("file") MultipartFile file) { String appKey = request.getHeader("appKey"); if (file.isEmpty()) { throw new AppBusinessException(UserErrorCode.BAD_REQUEST); } TDingApp app = TDingApp.dao.findFirst("select * from t_ding_app where app_alias=? ", appKey); if (null == app) { throw new AppBusinessException(UserErrorCode.NO_APPKEY); } String name = file.getOriginalFilename(); String suffix = name.substring(name.lastIndexOf(".") + 1).toLowerCase(); // String suffix = name.substring(name.lastIndexOf(".") + 1); List<String> fileTypes = Arrays.asList(types.split(",")); if (!fileTypes.contains(suffix)) { throw new AppBusinessException(UserErrorCode.UPLOAD_ERROR, "只能上传以下文件: " + fileTypes); } String fileName = null; try { fileName = this.aliyunOSSClientUtils.putFile(app.getOssFolder(), file.getInputStream(), suffix); } catch (IOException e) { e.printStackTrace(); throw new AppBusinessException(UserErrorCode.UPLOAD_ERROR, e.getMessage()); } Map<String, String> map = new HashMap<>(); map.put("newFileName", fileName); map.put("oldFileName", name); return ok(map); }
/** * @param folderName * @param fileInputStream * @param suffix * @date: 22:52 2019/7/22 * @return: String * 上传文件 **/ public String putFile(String folderName, InputStream fileInputStream, String suffix) throws IOException { if (null == fileInputStream) { throw new NullArgumentException("uploadFile参数不能为空"); } OSS ossClient = getDefaultOSSClient(); // String suffix = uploadFile.getName().substring(uploadFile.getName().lastIndexOf(".") + 1); String fileName = UUID.randomUUID().toString() + "." + suffix; String targetFile = ""; targetFile = fileName; if (null != folderName) { targetFile = folderName + "/" + fileName; } PutObjectResult putObjectResult = ossClient.putObject(bucket, targetFile, fileInputStream); fileInputStream.close(); ossClient.shutdown(); if (null == putObjectResult.getResponse()) { return targetFile; } return null; }