java实现给图片添加水印(文字水印或图片水印)
以下代码是为了实现,在上传图片时对其进行压缩,加文字或图片水印,最后再将处理好的图片url返回给前端,话不多少直接上源码。
//前端代码exportfunctionuploadArtWork(file, fileType, title){returnnewPromise((resolve, reject)=>{let url = window.baseUrl+'/project/client/file/fileUploadCompressUser';let userId =getUserId();let formData ={modular:'art_'+fileType,usedFileUrl:'',width:1000,userId: userId,title: title,voteCofigId:tempArtCfg.cfgId
}
uni.uploadFile({url: url,name:'file',
formData,file:file,success:(result=>{let data =JSON.parse(result.data);if(data.code ==200){let url = data.data;resolve(url)}else{
uni.hideLoading();
uni.showModal({title:'提示',content:data.msg,showCancel:false,});}}),fail:(result=>{reject(result)})})})}
//Cotorller层调用@Log("上传文件压缩处理")@PostMapping(value ="/fileUploadCompressUser")publicResponseEntity<R>fileUploadCompressUser(@RequestParam(name ="width", required =false)Integer width,@RequestParam(name ="usedFileUrl", required =false)String usedFileUrl,@RequestParam(name ="modular",required =false)String modular,@RequestParam(name ="file")MultipartFile file,@RequestParam(name ="title",required =false)String title,@RequestParam(name ="userId",required =false)Long userId,@RequestParam(name ="voteCofigId",required =false)Long voteCofigId)throwsException{R result =null;UserInfo me = userInfoRepository.get(userId,UserInfo.class);String username = me.getUsername();String mobile = me.getMobile();//判断是否图片,图片走压缩,String originalFilename = file.getOriginalFilename();String format=originalFilename.subSequence(originalFilename.lastIndexOf(".")+1, originalFilename.length()).toString();List<Map<String,Object>> voteCofigList = voteConfigRepository.findMapByNativeSql("SELECT video_size videoSize,is_water_mark isWaterMark,text_watermark textWatermark,image_watermark imageWatermark FROM vote_config WHERE id = :voteCofigId",newHashMap<String,Object>(){{put("voteCofigId",voteCofigId);}});if("jpg".equals(format)||"png".equals(format)||"jpeg".equals(format)||"gif".equals(format)){if(voteCofigList.get(0).size()>0){Boolean isWaterMark =Boolean.parseBoolean(voteCofigList.get(0).get("isWaterMark").toString());//如果需要添加水印if(isWaterMark){//从数据库中取文字水印或者图片水印(url)的值String textWatermark = voteCofigList.get(0).get("textWatermark")!=null?voteCofigList.get(0).get("textWatermark").toString():null;String imageWatermark = voteCofigList.get(0).get("imageWatermark")!=null?voteCofigList.get(0).get("imageWatermark").toString():null;
file =ImageUtil.addWatermark(textWatermark,imageWatermark,file);}}}else{String type = modular.substring(modular.lastIndexOf("_")+1);if(type.equals("video")){//如果有规定视频的大小不大于多少if(voteCofigList.get(0).size()>0){Integer videoSize =Integer.parseInt(voteCofigList.get(0).get("videoSize").toString());returnnewResponseEntity<>(VideoUtil.limitVideoCapacity(videoSize,file.getSize()),HttpStatus.OK);}}
width =0;returnfileUploadUser(width,usedFileUrl,modular,file,title,userId);}Map<String,Map<String,Object>> fileList =getFileUploadService().fileUploadCompressUser(file, width, title, username, mobile);Map<String,Object> r =newHashMap<>();R r1 =newR();String fileUrl ="";String realUrl ="";for(int i=1;i<=fileList.size();i++){Map<String,Object> map = fileList.get("fileName"+ i);
fileUrl =(String) map.get("realUrl");if(i!=1) realUrl =(String) map.get("realUrl");if(!"".equals(fileUrl)&& fileUrl !=null){
r.put("url"+i,fileUrl);OssFileList ossFileList =getOssFileList(modular, map, fileUrl);
ossFileListService.create(ossFileList);
ossFileListService.deleteInvalidFile(usedFileUrl);}else{
result =R.fail("文件上传失败");returnnewResponseEntity<>(result,HttpStatus.OK);}}// result = R.ok(fileUrl);
r1.setData(realUrl);
r1.setCode(200);
r1.setMsg("文件上传成功");returnnewResponseEntity<>(r1,HttpStatus.OK);}
packagecom.yuqiaotech.utils;importcom.yuqiaotech.fileUpload.FileUploadUtils;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.mock.web.MockMultipartFile;importorg.springframework.stereotype.Component;importorg.springframework.web.multipart.MultipartFile;importjavax.imageio.ImageIO;importjava.awt.*;importjava.awt.image.BufferedImage;importjava.io.*;importjava.net.MalformedURLException;importjava.net.URL;/**
* 图片工具
*/@ComponentpublicclassImageUtil{@AutowiredFileUploadUtils fileUploadUtils;publicstaticMultipartFileaddWatermark(String textWatermark,String imageWatermark,MultipartFile file){// 读取原图片信息 得到文件File srcImgFile =FileUtil.toFile(file);//将文件对象转化为图片对象Image srcImg =null;try{
srcImg =ImageIO.read(srcImgFile);}catch(IOException e){
e.printStackTrace();}//获取图片的宽int srcImgWidth = srcImg.getWidth(null);//获取图片的高int srcImgHeight = srcImg.getHeight(null);BufferedImage bufImg =newBufferedImage(srcImgWidth, srcImgHeight,BufferedImage.TYPE_INT_RGB);// 加水印//创建画笔Graphics2D graphics2D = bufImg.createGraphics();//绘制原始图片
graphics2D.drawImage(srcImg,0,0, srcImgWidth, srcImgHeight,null);//如果文字水印有值,就将其绘制在图的中间if(StringUtils.isNotEmpty(textWatermark)){addTextWatermark(graphics2D,srcImgWidth,srcImgHeight,textWatermark);}elseif(StringUtils.isNotEmpty(imageWatermark)){//如果图片水印有值,就将其绘制在图的右下角addImageWatermark(graphics2D,srcImgWidth,srcImgHeight,imageWatermark,4);}// //待存储的地址--测试用的// String tarImgPath="C:/Users/Administrator/Desktop/tx.png";// 输出图片// FileOutputStream outImgStream = null;ByteArrayOutputStream os =null;MultipartFile multipartFile =null;try{// outImgStream = new FileOutputStream(tarImgPath);// ImageIO.write(bufImg, "png", outImgStream);//创建一个ByteArrayOutputStream
os =newByteArrayOutputStream();//把BufferedImage写入ByteArrayOutputStream//此处要写PNG否则可能会出现遮罩层ImageIO.write(bufImg,"png", os);//ByteArrayOutputStream转成InputStreamInputStream input =newByteArrayInputStream(os.toByteArray());
multipartFile =newMockMultipartFile("file","file.png","text/plain", input);}catch(Exception e){
e.printStackTrace();}finally{try{if(null!= os){
os.close();}// if (null != outImgStream) {// outImgStream.flush();// outImgStream.close();// }}catch(FileNotFoundException e){
e.printStackTrace();}catch(IOException e){
e.printStackTrace();}}return multipartFile;}publicstaticvoidaddTextWatermark(Graphics2D graphics2D,int srcImgWidth,int srcImgHeight,String textWatermark){//-------------------------文字水印 start----------------------------//根据图片的背景设置水印颜色
graphics2D.setColor(newColor(255,255,255,128));//设置字体 画笔字体样式为微软雅黑,加粗,文字大小为60pt
graphics2D.setFont(newFont("微软雅黑",Font.BOLD,30));//设置水印的坐标(为原图片中间位置)//textWatermark为水印内容int x=(srcImgWidth -getWatermarkLength(textWatermark, graphics2D))/2;int y=srcImgHeight /2;//画出水印 第一个参数是水印内容,第二个参数是x轴坐标,第三个参数是y轴坐标
graphics2D.drawString(textWatermark, x, y);
graphics2D.dispose();//-------------------------文字水印 end----------------------------}publicstaticvoidaddImageWatermark(Graphics2D graphics2D,int srcImgWidth,int srcImgHeight,String imageWatermark,int type){//-------------------------图片水印 start----------------------------//水印文件//创建一个URL对象,获取网络图片的地址信息(网络图片)URL url =null;//将URL对象输入流转化为图片对象 (url.openStream()方法,获得一个输入流)Image srcWaterMark =null;try{
url =newURL(imageWatermark);
srcWaterMark =ImageIO.read(url.openStream());}catch(MalformedURLException e){
e.printStackTrace();}catch(IOException e){
e.printStackTrace();}//设置 alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字
graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,0.5f));//x,y为章需要合成到A图片上的位置坐标,w,h为将章缩小到多少长宽比例//注意这行代码:graphics2D.drawlmage(img, x, y, w, h, null);//绘制水印图片 坐标为自己选择int x =0;int y =0;int width =(int)(srcImgWidth*0.1);int height =(int)(srcImgWidth*0.1);if(type ==1){//覆盖图片位于左上角
x =0;
y =0;}elseif(type ==2){//覆盖图片位于右上角
x = srcImgWidth - width;
y =0;}elseif(type ==3){//覆盖图片位于左下角
x =0;
y = srcImgHeight - height;}elseif(type ==4){//覆盖图片位于右下角
x = srcImgWidth - width;
y = srcImgHeight - height;}elseif(type ==5){//覆盖图片位于中间
x =(srcImgWidth - width)/2;
y =(srcImgWidth - height)/2;}
graphics2D.drawImage(srcWaterMark, x, y ,width, height,null);// 水印文件结束
graphics2D.dispose();//-------------------------图片水印 end----------------------------}/**
* 获取水印文字的长度
* @param waterMarkContent
* @param graphics2D
* @return
*/publicstaticintgetWatermarkLength(String waterMarkContent,Graphics2D graphics2D){return graphics2D.getFontMetrics(graphics2D.getFont()).charsWidth(waterMarkContent.toCharArray(),0, waterMarkContent.length());}}
java实现给图片添加水印(文字水印或图片水印)
原文是这位作者的,调理清晰且很好用!
版权归原作者 唐人街都是苦瓜脸 所有, 如有侵权,请联系我们删除。