8、图片加水印

原创
2017/07/17 18:10
阅读数 128
AI总结

这两天将图片水印实践了下,代码如下,共保存记忆。

前端JSP页面如下

<%@page import="java.util.List"%>
<%@page import="com.dimensions.entity.AdsTemplates" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib uri="/struts-layout-tags" prefix="layout"%>
<layout:content_for name="title">广告-模板</layout:content_for>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
	String ad_position = (String)request.getAttribute("ad_position");
	List<AdsTemplates> listAdsTemplatesUrl = (List<AdsTemplates>)request.getAttribute("listAdsTemplatesUrl");
%>
<style>
  #moreBut:hover{
  	cursor:pointer
  }
  .imgtem:hover{
  	cursor:pointer
  }
  #freeTemplate span{
  	width:60%;
  	height:70%;
  	display:block;
  	margin-left:20%;
  	letter-spacing:1.2em;
  }
  #freeTemplate span a{
  	color:#FFF;
  	font-size:16px;
  	font-weight:bold;
  	line-height:250%;
  }
  #adsbutton span{
  	margin-left:7px;
  }
  #adsbutton span a{
  	color:#FFF;
  	font-size:16px;
  	line-height:150%;
  }
  #adsbutton span a:hover{
  	cursor:pointer;
  }
  #companyName{
  	margin:0 auto;
  }
  #companyName input{
  	width:100%;
  	height:100%;
  	font-size:30px;
  	text-align:center;
  	letter-spacing:0.6em; 
  	background:rgba(0, 0, 0, 0);
  }
  #companyConn{
  	margin:0 auto;
  }
  #companyConn table{
  	width:100%;
  	height:100%;
  	text-align:left;
  	vertical-align:middle;
  }
  .ccWord a{
  	font-size:26px;
  	color:#59493F;
  }
  #companyConn table td input{
   	width:100%;
   	height:70%;
   	font-size:22px;
  	text-align:left;
  	background:rgba(0, 0, 0, 0);
  	border:1px solid #000;
  }
  #formSubmitBtn:hover{
  	cursor:pointer
  }
  #formSubmitBtn span{
  	width:30%;
  	height:100%;
  	display:block;
  	margin:0 auto;
  }
  #formSubmitBtn span a{
  	font-size:20px;
  	letter-spacing:0.6em;
  	color:#FFF;
  	line-height:180%;
  }
</style>
<script type="text/javascript">
$(function(){
	var adsTcWidth = (document.body.offsetWidth)*0.64;
	var adsTcHeight = ((document.body.offsetWidth)*0.64)*0.8542;
	$("#adsTemplatesContent").css({
		"width":adsTcWidth+"px",
		"height":adsTcHeight+"px",
		"border":"1px solid #A8A8A8",
		"margin-left":"17%",
		"overflow":"hidden"
	});
	
	var freeTemplateWidth = adsTcWidth*0.2667;
	var freeTemplateHeight = freeTemplateWidth*0.18;
	$("#freeTemplate").css({
		"width":freeTemplateWidth+"px",
		"height":freeTemplateHeight+"px",
		"background-color":"#706054",
		"margin-top":"15px",
		"margin-left":-(freeTemplateWidth*0.27)+"px",
		"transform":"rotate(-45deg)",
	});
	
	var adsbuttonWidth = adsTcWidth*0.1875;
	var adsbuttonHeight = adsbuttonWidth*0.1667;
	var adsbuttonTop = $("#adsTemplatesContent").position().top;
	var adsbuttonLeft = $("#adsTemplatesContent").position().Left;
	$("#adsbutton").css({
		"width":adsbuttonWidth+"px",
		"height":adsbuttonHeight+"px",
		"background-color":"#706054",
		"margin-top":(10-freeTemplateHeight)+"px",
		"margin-left":(adsTcWidth-adsbuttonWidth-8)+"px"
	});
	
	var companyNameWidth = adsTcWidth*0.7625;
	var companyNameHeight = companyNameWidth*0.1093;
	$("#companyName").css({
		"width":companyNameWidth+"px",
		"height":companyNameHeight+"px",
		"margin-top":"6%",
		"border":"2px dashed #FFF"
	});
	
	var companyConnHeight = adsTcHeight*0.3805;
	$("#companyConn").css({
		"width":companyNameWidth+"px",
		"height":companyConnHeight+"px",
		"margin-top":"8%",
	});
	
	var formSubmitBtnWidth = adsTcWidth*0.2625;
	var formSubmitBtnHeight = formSubmitBtnWidth*0.1733;
	$("#formSubmitBtn").css({
		"width":formSubmitBtnWidth+"px",
		"height":formSubmitBtnHeight+"px",
		"background-color":"#6CBEF6",
		"margin":"0 auto",
		"margin-top":"20px"
	});
	
	$("#moreBut").click(function(){
		var atDisplay = $("#adsTemplates").css("display");
		$("#adsTemplates").slideToggle();
		if(atDisplay=="block"){
			$("#moreBut").text("更多∨");
		}else{
			$("#moreBut").text("收起∧");
		}
	});
	
	$("#changeButton").click(function(){
		
	});
	
	$("#cancelButton").click(function(){
		$("#adsTemplatesContent").css({
			"background-image":('url("")'),
			"background-repeat":"",
			"background-size":""
		});
	});
	
	$("#formSubmitBtn").click(function(){
		var companyName = $("#companyConnForm").find("input[name='companyName']").val();
		var imgageUrl = $("#companyConnForm").find("input[name='imgageUrl']").val();
		var linkman = $("#companyConnForm").find("input[name='linkman']").val();
		var address = $("#companyConnForm").find("input[name='address']").val();
		var majorBus = $("#companyConnForm").find("input[name='majorBus']").val();
		var contactNum = $("#companyConnForm").find("input[name='contactNum']").val();
		if(companyName==undefined || companyName.trim()=="请在这里输入公司名称" || companyName==null){
			alert("公司名称不能为空.");
			return false;
		}
		if(imgageUrl==undefined ||imgageUrl.trim()=="" || imgageUrl==null){
			alert("请选择背景图片.");
			return false;
		}
		if(linkman==undefined ||linkman.trim()=="" || linkman==null){
			alert("请输入联系人.");
			return false;
		}
		if(address==undefined ||address.trim()=="" || address==null){
			alert("请输入地址.");
			return false;
		}
		if(majorBus==undefined ||majorBus.trim()=="" || majorBus==null){
			alert("请输入主营业务.");
			return false;
		}
		if(contactNum==undefined ||contactNum.trim()=="" || contactNum==null){
			alert("请输入联系电话.");
			return false;
		}
		
		$("#companyConnForm").submit();
		
	});
});
function imgtemBack(node){
	var backImgUrl = $(node).children("img").attr("src");
	console.log(backImgUrl);
	$("#adsTemplatesContent").css({
		"background-image":('url("'+backImgUrl+'")'),
		"background-repeat":"no-repeat",
		"background-size":"100% 100%"
	});
	$("#companyConnForm").find("input[name='imgageUrl']").val(backImgUrl);
}
</script>
<div style="margin:0 auto;width:100%;min-height:600px;background-color:#FFF;">
	<div style="width:16%;height:30px;border:1px solid #E5E5E5;background-color:#F0F0F0;margin-left:17%;">
		<span style="margin-left:10px;"><a style="line-height:30px;font-size:14px;font-family:'Microsoft YaHei'">模板:</a></span>
		<div id="moreBut" style="width:35px;height:20px;background-color:#FFF;border:1px solid #81CCED;float:right;margin-top:5px;margin-right:5px;">更多∨</div>
	</div>
	<div id="adsTemplates" style="display:none;width:64%;height:160px;padding-top:10px;border:1px solid #E5E5E5;margin-left:17%;">
		<%
			for(int i=0;i<listAdsTemplatesUrl.size();i++){
		%>
			<div style="width:90px;height:140px;border:1px solid #A6A6AA;margin-left:20px;float:left;">
				<div style="width:80px;height:100px;margin:4px;border-radius:7px;">
					<a href="javascript:void(0);" onclick="imgtemBack(this)"><img id="imgtem<%=i %>" class="imgtem" style="width:100%;height:100%;" alt="img" src="<%=basePath %>/<%=listAdsTemplatesUrl.get(i).getUrl()%>"></a>
				</div>
				<div style="width:80px;height:20px;margin-left:4px;text-align:center;">
					<a>清凉(<%=i+1 %>)夏</a>
				</div>
			</div>
		<% 
			} 
		%>
	</div>
	<div id="adsTemplatesContent">
		<div id="freeTemplate">
			<span><a>免费模板</a></span>
		</div>
		<div id="adsbutton">
			<span id="changeButton"><a>更换模板</a></span>
			<span><a>|</a></span>
			<span id="cancelButton"><a>取消模板</a></span>
		</div>
		<form id="companyConnForm" action="<%=request.getContextPath()%>/manage/manufactureAdsTemplates.action" method="post" style="width:100%;height:100%;">
			<div id="companyName">
				<input type="text" name="companyName" value="请在这里输入公司名称" onBlur="javascript:if(this.value.trim()=='')this.value='请在这里输入公司名称';" onfocus="javascript:if(this.value=='请在这里输入公司名称')this.value='';"/>
			</div>
			<div id="companyConn">
					<table>
						<tr>
							<td width="30%" class="ccWord"><a>
								<input type="hidden" name="imgageUrl"/>
								<input type="hidden" name="ad_position" value="<%=ad_position %>">
								主&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;营:</a></td>
							<td width="70%"><input type="text" name="majorBus" onkeyup="if(this.value.length>30){this.value = this.value.substring(0,30);}"/></td>
						</tr>
						<tr>
							<td width="30%" class="ccWord"><a>联系&nbsp;&nbsp;&nbsp;&nbsp;人:</a></td>
							<td width="70%"><input type="text" name="linkman"/></td>
						</tr>
						<tr>
							<td width="30%" class="ccWord"><a>联系电话:</a></td>
							<td width="70%"><input type="text" name="contactNum"/></td>
						</tr>
						<tr>
							<td width="30%" class="ccWord"><a>地&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;址:</a></td>
							<td width="70%"><input type="text" name="address" onkeyup="if(this.value.length>20){this.value = this.value.substring(0,20);}"/></td>
						</tr>
					</table>
			</div>
		</form>
	</div>
	
	<div id="formSubmitBtn">
		<span><a>确定</a></span>
	</div>
</div>

Action 层代码如下:

package com.dimensions.action.manage;

import java.net.URLEncoder;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.dimensions.action.Action;
import com.dimensions.dao.AdsTemplatesDao;
import com.dimensions.entity.AdsTemplates;
import com.dimensions.service.AdsTemplatesService;
import com.dimensions.utils.UrlUtils;
import com.google.inject.Inject;
/**
 * 类描述: 广告模板类
 * @author lee
 * @date 2017年7月13日 下午14:45:01
 */
@SuppressWarnings("serial")
public class AdsTemplatesAction extends Action {

	@Inject
	private AdsTemplatesDao adsTemplatesDao;
	@Inject
	private AdsTemplatesService adsTemplatesService;
	/**
	 * 跳转到使用模板界面
	 * @return
	 */
	public String templates(){
		String ad_position = request.getParameter("ad_position");
		List<AdsTemplates> listAdsTemplatesUrl = adsTemplatesDao.query("select url from ads_templates order by position", false);
		request.setAttribute("ad_position", ad_position);
		request.setAttribute("listAdsTemplatesUrl", listAdsTemplatesUrl);
		return "templates";
	}
	
	/**
	 * 定制 用户广告模板
	 */
	public String manufacture(){
		String ad_position = request.getParameter("ad_position");
		String companyName = request.getParameter("companyName");
		String imgageUrl = request.getParameter("imgageUrl");
		String linkman = request.getParameter("linkman");
		String address = request.getParameter("address");
		String majorBus = request.getParameter("majorBus");
		String contactNum = request.getParameter("contactNum");
		request.setAttribute("ad_position", ad_position);
		if(StringUtils.isNotBlank(companyName)
				&& StringUtils.isNotBlank(imgageUrl) && StringUtils.isNotBlank(linkman)
				&& StringUtils.isNotBlank(linkman) && StringUtils.isNotBlank(address)
				&& StringUtils.isNotBlank(majorBus) && StringUtils.isNotBlank(contactNum)){
			String imgUrl = adsTemplatesService.manufacture(imgageUrl,companyName,majorBus,linkman,contactNum,address,request.getRealPath("/"),this.getUser_id());
			String httpUrl = UrlUtils.generateDomainUrl(request)+imgUrl;
			request.setAttribute("adsTemplateUrl", URLEncoder.encode(httpUrl));
			return "addAds";
		}else{
			return "manufacture";
		}
	}
}

service层代码如下

/**
	 * 用户提供的信息--打印相应的水印信息
	 * @param address 
	 * @param contactNum 
	 * @param linkman 
	 * @param majorBus 
	 * @param companyName 
	 * @param imgageUrl 
	 */
	public String manufacture(String imgageUrl, String companyName, String majorBus, String linkman, 
						String contactNum, String address,String savePath,Integer userId){
		
		if(StringUtils.isNotBlank(imgageUrl)){
			try {
				//读取原图片信息
				URL url =new URL(imgageUrl);
				InputStream srcImgStream=url.openStream();
				Image srcImg = ImageIO.read(srcImgStream);
				int srcImgWidth = srcImg.getWidth(null);//获取图片的宽度和高度
				int srcImgHeight = srcImg.getHeight(null);
				
				
				//加水印
				BufferedImage bufImg =	new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
				Graphics2D g = bufImg.createGraphics();
				g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
				
				//公司名称
				g.setFont(new Font("微软雅黑", Font.BOLD, 38));
				g.setColor(new Color(89,72,63,255));
				float companyX = (srcImgWidth - getWatermarkLength(companyName, g))/2;
				float companyY = (float) (srcImgHeight*0.222);
				g.drawString(companyName,companyX , companyY);
				
				//主营
				g.setFont(new Font("微软雅黑", Font.BOLD, 26));
				g.setColor(new Color(77,51,40,255));
				float captionX = (float) ((srcImgWidth-(srcImgWidth*0.7025))/2);
				float captionY = (float)(companyY*1.8);
				float contentX = (float) (captionX+srcImgWidth*0.203); 
				g.drawString("主       营:",captionX , captionY);
				if(majorBus.length()<16){
					g.drawString(majorBus,contentX , captionY);
					g.drawString("联  系 人:",captionX , (float)(captionY+srcImgHeight*0.1032));
					g.drawString(linkman,contentX , (float)(captionY+srcImgHeight*0.1032));
					g.drawString("联系电话:",captionX , (float)(captionY+srcImgHeight*0.1032*2));
					g.drawString(contactNum,contentX , (float)(captionY+srcImgHeight*0.1032*2));
					g.drawString("地       址:",captionX , (float)(captionY+srcImgHeight*0.1032*3));
					g.drawString(address,contentX ,(float)(captionY+srcImgHeight*0.1032*3));
				}else{
					if(majorBus.length()>30){
						majorBus = majorBus.substring(0, 30);
					}
					g.drawString(majorBus.substring(0, 15),contentX , captionY);
					g.drawString(majorBus.substring(15, majorBus.length()),contentX, (float)(captionY+srcImgHeight*0.1032*0.7));
					g.drawString("联  系 人:",captionX , (float)(captionY+srcImgHeight*0.1032*1.7));
					g.drawString(linkman,contentX , (float)(captionY+srcImgHeight*0.1032*1.7));
					g.drawString("联系电话:",captionX , (float)(captionY+srcImgHeight*0.1032*2.7));
					g.drawString(contactNum,contentX , (float)(captionY+srcImgHeight*0.1032*2.7));
					g.drawString("地       址:",captionX , (float)(captionY+srcImgHeight*0.1032*3.7));
					g.drawString(address,contentX ,(float)(captionY+srcImgHeight*0.1032*3.7));
				}
				
				
				
				g.dispose();
				//输出图片
				String fileName =UUID.randomUUID()+".png";
			
				//数据库保存图片信息
				UploadedImages uploadedImages = new UploadedImages();
				uploadedImages.setContent_type("image/png");
				uploadedImages.setFilename(fileName);
				uploadedImages.setCreated_by(userId);
				uploadedImages.setCreated_at(DateUtils.currentDateTime());
				//uploadedImages.setSize("不知道");
				uploadedImages.setWidth(srcImgWidth);     //得到图片的宽度
				uploadedImages.setHeight(srcImgHeight);   //得到图片的高度
				uploadedImagesDao.insert(uploadedImages);
				
				
				//创建存储路径
				Integer uploaded_image_id = uploadedImagesDao.lastInsertId().intValue();
				String newurl = ImageUtils.buildTopicPath(uploaded_image_id+"") +"/"+fileName;
				String outFilepath = savePath+"/uploaded_images/"+ newurl;
				File savePathFile = new File(savePath+"/uploaded_images/"+ImageUtils.buildTopicPath(uploaded_image_id+"") +"/");
				if(!savePathFile.exists()){
					savePathFile.mkdirs();
				}
				FileOutputStream outImgString = new FileOutputStream(outFilepath);
				ImageIO.write(bufImg, "png", outImgString);
				System.out.println("====水印添加完成=====");
				outImgString.flush();
				outImgString.close();
				
				return "/uploaded_images/"+newurl;
			} catch (IOException e) {
				e.printStackTrace();
			} catch (DaoException e) {
				e.printStackTrace();
			}
		}
		return "";
	}
	
	/**
	 * 获取水印长度
	 */
	public float getWatermarkLength(String waterMarkContent, Graphics2D g) {  
		return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());  
	}

最终效果:

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
AI总结
返回顶部
顶部