• html5画图板


    并发组合代码部分H.java有问题,没进行处理

    不会js,记事本开发,没优化。。




    index.jsp首页

    <%@ page language="java" contentType="text/html; charset=GBK"%>
    <%@ page import="javab.R" %> 
    <%@ page import="javab.U" %>
    <%
    	String root  = request.getRealPath("/");
    	R r = new R();
    	int num = r.getNum(root);
    	num= num+30000;
    
    	U u = new U();
    	u.add(root);
    %>
    
    <style type="text/css">
    
    .bc {
    	 908px;
    	height: 109px;
    	border: 0px solid #000;
    	position: fixed;
    	left: 50%;
    	
    	bottom:1%;
    	margin-left: -454px;
    	margin-top: -109px;
    	_position: absolute;
    	_top: expression(eval(document.documentElement.clientHeight+document.documentElement.scrollTop;));
    	_left: expression(eval(document.documentElement.clientWidth/2+document.documentElement.scrollLeft;));
    }
    
    .dcc {
    	 600px;  
        height: 100px;  
        border: 0px solid #000;  
        position: fixed;  
        left: 50%;  
        top: 50%;  
        margin-left: -300px;  
        margin-top: -100px;  
        _position: absolute;  
        _top: expression(eval(document.documentElement.clientHeight/2+document.documentElement.scrollTop;));  
        _left: expression(eval(document.documentElement.clientWidth/2+document.documentElement.scrollLeft;)); 
    	
    }
    
    .all {
    height:100%;
    position:absolute; 
    100%;
    }
    
    </style>
    <!-- 
    动态设置div布局的方法
    -->
    <html>
    <head>
    
    <meta name = "viewport" content = "user-scalable = yes">
        <meta name="screen-orientation" content="portrait"/>
        <meta name="apple-mobile-web-app-capable" content="yes"/>
       
    <title>标题</title>
    
    <script>
    function onClickBg(event)
    {
        var obj 
    	if (document.all) 
    	{ 
    		obj = window.event.srcElement;    
    	} 
    	else 
    	{ 
    		obj = event.target; 
    	} 
    	if (obj.id == "dv2")//避免点击dv2时点击到BackGround
    	{ 
    		return; 
    	} 
    	//alert('bg');
    
    	var url = "png.jsp?type=0";
    	window.open(url)
    }
    
    function onClickButton(event)
    {
    	var url = "paint.html";
    	window.open(url)
    }
    
    </script>
    </head>
    <center>
    <body>
    <!--
    <div class = "dcc">
    <font size="10">已有<%=num%>个用户签名承诺</font><font size="10" color="red">》</font>
    </div>
    -->
    
    <div id="dv1" onclick="onClickBg(event)">
    	<img src="image/bg1.png"></img>
    </div>
    
    <div onclick="onClickBg(event)">
    <font size="10">已有<%=num%>个用户签名承诺</font><font size="10" color="red">》</font>
    </div>
    
    <div id="dv1" onclick="onClickBg(event)">
    	<img src="image/bg2.png"></img>
    </div>
    
    <div id="dv2"  class="bc" onclick="onClickButton(event)">
    <img src="image/btmbutton.png"></img>
    </div>
    
    </body>
    </center>
    </html>


    paint.jsp 画图程序(可以上传到后台)

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=GBK" />
        <meta name = "viewport" content = "width = device-width, user-scalable = no">
        <meta name="screen-orientation" content="portrait"/>
        <meta name="apple-mobile-web-app-capable" content="yes"/>
        <meta name="full-screen" content="yes"/>
        <meta name="x5-fullscreen" content="true"/>
    	
    <title>标题</title>
    	<style>
    		#colorBoard{position:absolute; padding:10px; 256px; height:220px; background:#f3f3f3; border:#d9d9d9 1px solid;}
    		#colorBank{ clear:both; border:#d9d9d9 1px solid; background:#FFF; 252px; padding:0 0 2px 2px; overflow:hidden; margin:0 auto 0 auto;}
    		#colorBank div{ overflow:hidden; height:12px; 12px; margin:2px 2px 0 0; float:left; overflow:hidden; cursor:pointer;}
    		#colorViews{80px; height:20px; float:left;border:#d9d9d9 1px solid; background:#000; display:block; margin: 0 10px 10px 0;}
    		#colorInput{70px; height:18px; float:left; font-family:Verdana; font-size:13px; color:#333; display:block; border:none; background:#FFF;border:#d9d9d9 1px solid;margin: 0 10px 10px 0;}
    		#colorClose{80px; color:#999999; height:22px; float:left;display:block; background:#f3f3f3;cursor:pointer;border:#d9d9d9 1px solid; border-top:#FFF 1px solid; border-left:#FFF 1px solid;}
    		
    		#divp{position:relative;}
    		#canvasp{position:absolute;top:0px;left:0px;}
    </style>
    	
    
    	
    
    </head>
    <body style="padding:0; margin: 0; background: #FFFFFF;">
    	
    
    	<div id="divp">
    		<div id="canvasp"><canvas id="canvasTop"></canvas></div>
    		<div id="id2"><canvas id="canvas"></canvas></div>
    	</div>
    
    	
    	<table border="0" style="margin-left:0px;">
    		
    		<tr>
    			<td><div id="pageColorViews" style="background:#000; 50px; height:50px;" onclick="colorSelect('pageColorViews',event)">
    			<img src="image/color.png"  style="50px; height:50px;"/>
    			</div></td>
    			<td>
    				<select id="sel" onchange="changeForm(this.value)">
    					
    					<option value="2">2</option>
    					
    					<option value="4">4</option>
    					
    					<option value="6">6</option>
    					
    					<option value="8">8</option>
    					
    					<option value="10" selected>10</option>
    					
    					<option value="12">12</option>
    					
    					<option value="14">14</option>
    					
    					<option value="16">16</option>
    					
    					<option value="18">18</option>
    					
    					<option value="20">20</option>
    					
    					<option value="22">22</option>
    					
    					<option value="24">24</option>
    					
    					<option value="26">26</option>
    					
    					<option value="28">28</option>
    					
    					<option value="30">30</option>
    					
    					<option value="32">32</option>
    					
    					<option value="34">34</option>
    					
    					<option value="36">36</option>
    					
    					<option value="38">38</option>
    					
    					<option value="40">40</option>
    					
    					<option value="60">60</option>
    					
    					<option value="80">80</option>
    					
    					<option value="100">100</option>
    					
    					<option value="200">200</option>
    				</select>
    			</td>
    
    			<td>
    				<img src="image/pen.png"  style="50px; height:50px;" onclick="penEvent()"/>
    			</td>
    			<td>
    				<img src="image/er.png" style="50px; height:50px;" onclick="erEvent()"/>
    			</td>
    			<td>
    				<img src="image/save.png" style="100px; height:50px;" onclick="saveEvent()"/>
    			</td>
    			<!-- 
    			<td>
    				<form name="myForm" method ="post" action = "t.jsp">
    				<input type=hidden name="hid" value="" id="hid">
    				<input type="button" value="save" onclick="saveEvent()" style=" 30px; height:30px;  border:0; background:url(image/save.png) no-repeat left top"">
    				</form>
    			</td>
    			-->
    		</tr>
    	</table>
    
    	<script type="text/javascript" src="canvasScript.js"></script>
    
    </body>
    </html>
    

    canvasScript.js  js画图板代码

    document.ondragstart=function()//禁止ie拖拽
    {
    	return false;
    }
    var bdrawed = 0;
    //绘图层
    var canvas = document.getElementById("canvas");
    //橡皮层
    var canvasTop = document.getElementById("canvasTop");
    //画笔颜色
    var colorValue = "#000000";
    //画笔粗细
    var size = 10;
    //0 pen 1 eraser
    var state = 0;
    //0 false 1 true
    var beMouseDown = 0;
    //设置canvas属性
    canvas.width=window.innerWidth;
    canvas.height=window.innerHeight-50;
    canvasTop.width=window.innerWidth;
    canvasTop.height=window.innerHeight-50;
    
    //上一次触摸点
    var lastX;
    var lastY;
    
    //获取画笔
    var ctx =canvas.getContext("2d");
    var ctx1 =canvasTop.getContext("2d");
    
    //设置画笔属性
    ctx.lineWidth=size;//画笔粗细
    ctx.strokeStyle=colorValue;//画笔颜色
    
    window.onload=function(){
    	 //reurl();
    	bdrawed = 0;
    	//是否支持触摸
    var touchable = 'createTouch' in document;
    if (touchable) {
    	//触屏事件
        canvas.addEventListener('touchstart', onTouchStart, false);
        canvas.addEventListener('touchmove', onTouchMove, false);
    	canvas.addEventListener('touchend', onTouchEnd, false);
    
    	canvasTop.addEventListener('touchstart', onTouchStart, false);
        canvasTop.addEventListener('touchmove', onTouchMove, false);
    	canvasTop.addEventListener('touchend', onTouchEnd, false);
    }
    else
    {
    	//浏览器鼠标事件
    	canvasTop.addEventListener('mousemove', onMouseMove, false);
        canvasTop.addEventListener('mouseup', onMouseUp, false);
    	canvasTop.addEventListener('mousedown', onMouseDown, false);
    }
    
    }
    
    function reurl(){//刷新页面一次
       url = location.href; //把当前页面的地址赋给变量 url
       var times = url.split("&"); //分切变量 url 分隔符号为 "?"
       if(times[1] != 1){ //如果?后的值不等于1表示没有刷新
        url += "&1"; //把变量 url 的值加入 ?1
    
    	//alert(url);
        self.location.replace(url); //刷新页面
       }
    }
    
    
    
    
    //鼠标按下事件
    function onMouseDown(event){
    	event.preventDefault();
    	bdrawed =1;
    	beMouseDown = 1;
      lastX=event.clientX;
      lastY=event.clientY;
    	ctx.strokeStyle=colorValue;//画笔颜色
    	ctx.lineWidth=size;
    	
    	if(state>0)
    	{
    		clean(lastX,lastY);
    		//橡皮绘制,在canvasTop层
    		drawEreser(lastX,lastY);
    	}
    	else
    	{
    		drawRound(lastX,lastY);//橡皮
    	}
    }
    
    //鼠标抬起事件
    function onMouseUp(event){
    	beMouseDown = 0;
    	if(state>0)
    	{
    		//清理canvasTop层
    		ctx1.clearRect(0,0,canvasTop.width,canvasTop.height);
    	}
    }
    
    //鼠标滑动事件
    function onMouseMove(event){
    	if(beMouseDown<1){return;}
    	try
    	{
    		event.preventDefault();
    		if(state>0)
    		{
    			clean(lastX,lastY);
    			drawEreser(lastX,lastY,size,size);
    			//drawEreser(event.clientX,event.clientY);
    		}
    		else
    		{
    			drawLine(lastX,lastY,event.clientX,event.clientY);
    		}  
      lastX=event.clientX;
      lastY=event.clientY;
    
    }
    catch(err){
           alert( err.description);
     }
    }
    
    //触摸开始事件
    function onTouchStart(event) {
    	//alert('touch');
    	bdrawed =1;
        event.preventDefault();
        lastX=event.touches[0].clientX;
        lastY=event.touches[0].clientY;
    		ctx.strokeStyle=colorValue;//画笔颜色
    		ctx.lineWidth=size;
    
    		if(state>0)
    		{
    			clean(lastX,lastY);
    			drawEreser(lastX,lastY);
    		}
    		else
    		{
    			drawRound(lastX,lastY);//橡皮
    		}
    }
    
    
    //触摸滑动事件
    function onTouchMove(event) {
    	try
      {
      	event.preventDefault();
    		if(state>0)
    		{
    			clean(lastX,lastY);
    			drawEreser(lastX,lastY,size,size);
    		}
    		else
    		{
    			drawLine(lastX,lastY,event.touches[0].clientX,event.touches[0].clientY);
    		}
    
        lastX=event.touches[0].clientX;
        lastY=event.touches[0].clientY;
    
        }
        catch(err){
            alert( err.description);
        }
    
    }
    
    function onTouchEnd(event) {
    	
    	if(state>0)
    	{
    	//清理canvasTop层
    		ctx1.clearRect(0,0,canvasTop.width,canvasTop.height);
    	}
    }
    
    //橡皮擦除指定区域
    function clean(x,y)
    {
    	var len = size/2;
    	ctx.clearRect(x-len,y-len,size,size);
    }
    
    //画橡皮(画框)
    function drawEreser(x,y)
    {
    	ctx1.clearRect(0,0,canvasTop.width,canvasTop.height);
    	ctx1.beginPath();
    	ctx1.lineWidth="2";
    	ctx1.strokeStyle="red";
    	var len = size/2;
    	ctx1.rect(x-len,y-len,size,size);
    	ctx1.stroke();
    }
    
    
    //画圆
    function drawRound(x,y)
    {
        ctx.fillStyle=colorValue;
        ctx.beginPath();
        ctx.arc(x,y,size/2,0,Math.PI*2,true);
        ctx.closePath();
        ctx.fill();
    }
    
    //画线
    function drawLine(startX,startY,endX,endY)
    {
        ctx.beginPath();
        ctx.lineCap="round";
        ctx.moveTo(startX,startY);
        ctx.lineTo(endX,endY);
        ctx.stroke();
    }
    
    
    
    //调色板----------------------------------------------------------------------------------
    
    
    function colorSelect(page,e){
     if(document.getElementById("colorBoard")){
      return;
     }
     //关于出现位置
     e=e||event;
     var scrollpos = getScrollPos();
     var l = scrollpos.l + e.clientX;
        var t = scrollpos.t + e.clientY + 10-255;
        if (l > getBody().clientWidth-253){
            l = getBody().clientWidth-253;
        }
     //创建DOM
     //var colorValue="#FF0000";//画笔颜色
     //var nowColor = document.getElementById(now);
     var pageColorViews = document.getElementById(page);
     var ColorHex=new Array('00','33','66','99','CC','FF');
     var SpColorHex=new Array('FF0000','00FF00','0000FF','FFFF00','00FFFF','FF00FF');
    
     var colorBank = document.createElement("div");
     colorBank.setAttribute("id","colorBank");
    
     var colorViews = document.createElement("div");
     colorViews.setAttribute("id","colorViews");
    
     var colorInput = document.createElement("input");
     colorInput.setAttribute("id","colorInput");
     colorInput.setAttribute("type","text");
     colorInput.setAttribute("disabled","disabled");
    
     var colorClose = document.createElement("input");
     colorClose.setAttribute("id","colorClose");
     colorClose.setAttribute("value","close");
     colorClose.setAttribute("type","button");
     colorClose.onclick=function(){document.body.removeChild(colorBoard)};
    
     var colorBoard =document.createElement("div");
     colorBoard.id="colorBoard";
     colorBoard.style.left = l+"px";
     colorBoard.style.top = t+ "px";
     colorBoard.appendChild(colorViews);
     colorBoard.appendChild(colorInput);
     colorBoard.appendChild(colorClose);
     colorBoard.appendChild(colorBank);
     document.body.appendChild(colorBoard);
    
     //循环出调色板
     for(b=0;b<6;b++){
      for(a=0;a<3;a++){
       for(i=0;i<6;i++){
        colorItem = document.createElement("div");
        colorItem.style.backgroundColor="#"+ColorHex[a]+ColorHex[i]+ColorHex[b];
        colorBank.appendChild(colorItem);
       }
      }
     }
    
     for(b=0;b<6;b++){
      for(a=3;a<6;a++){
       for(i=0;i<6;i++){
        colorItem = document.createElement("div");
        colorItem.style.backgroundColor="#"+ColorHex[a]+ColorHex[i]+ColorHex[b];
        colorBank.appendChild(colorItem);
       }
      }
     }
    
     for(i=0;i<6;i++){
      colorItem = document.createElement("div");
      colorItem.style.backgroundColor="#"+ColorHex[0]+ColorHex[0]+ColorHex[0];
      colorBank.appendChild(colorItem);
     }
    
     for(i=0;i<6;i++){
      colorItem = document.createElement("div");
      colorItem.style.backgroundColor="#"+ColorHex[i]+ColorHex[i]+ColorHex[i];
      colorBank.appendChild(colorItem);
     }
    
     for(i=0;i<6;i++){
      colorItem = document.createElement("div");
      colorItem.style.backgroundColor="#"+SpColorHex[i];
      colorBank.appendChild(colorItem);
     }
    
     var colorItems = colorBank.getElementsByTagName("div");
     for(i=0; i<colorItems.length;i++){
      colorItems[i].onmouseover = function(){
       a = this.style.backgroundColor;
       if(a.length>7){
        a = formatRgb(a);//
       }
       colorViews.style.background = a.toUpperCase();
       colorInput.value = a.toUpperCase();
      }
      colorItems[i].onclick = function(){
       a = this.style.backgroundColor;
       if(a.length>7){
        a = formatRgb(a);//
       }
       colorValue = a.toUpperCase();
       ctx.strokeStyl = colorValue;
       pageColorViews.style.background = a.toUpperCase();
       document.body.removeChild(colorBoard);
      }
     }
    }
    
    //格式化函数
    function formatRgb(rgb){
     rgb = rgb.replace("rgb","");rgb = rgb.replace("(","");rgb = rgb.replace(")","");
     format = rgb.split(",");
     a = eval(format[0]).toString(16);
     b = eval(format[1]).toString(16);
     c = eval(format[2]).toString(16);
     rgb = "#"+checkFF(a)+checkFF(b)+checkFF(c);
     function checkFF(str){
      if(str.length == 1){
       str = str+""+str;
       return str;
      }else{
       return str;
      }
     }
     return rgb;
    }
    //getBody()
    function getBody(){
        var Body;
        if (typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat') {
           Body = document.documentElement;
        }
        else if (typeof document.body != 'undefined') {
           Body = document.body;
        }
        return Body;
    }
    
    //scrollPos
    function getScrollPos(){
      var t,l;
      if (typeof window.pageYOffset != 'undefined'){
        t = window.pageYOffset;
        l = window.pageXOffset;
      }
      else{
       t = getBody().scrollTop;
       l = getBody().scrollLeft;
      }
      return {t:t,l:l};
    }
    
    //选择列表触发事件
    function changeForm(val){
    	size = val;		
    }
    
    //铅笔事件
    function penEvent(){
    	state = 0;
    }
    
    //橡皮事件
    function erEvent(){
    	state =1;
    }
    
    //保存事件
    function saveEvent(){
    
    if(bdrawed <1)
    {
    	alert('请签名后再上传吧~');
    	return;
    }
    
    var mycanvas = document.getElementById("canvas");
    var imaged    = mycanvas.toDataURL("image/png");
    var b64 = imaged.substring( 22 );
    
    //var url = "http://192.168.1.103:8080/html5Paint/html5/t.jsp?hid="+b64;
    //window.open(url)
    
    var url = "t.jsp";
    post(url, {hid :b64}); 
    }
    
    function post(URL, PARAMS) {      
        var temp = document.createElement("form");      
        temp.action = URL;      
        temp.method = "post";      
        temp.style.display = "none";      
        for (var x in PARAMS) {      
            var opt = document.createElement("textarea");      
            opt.name = x;      
            opt.value = PARAMS[x];      
            // alert(opt.name)      
            temp.appendChild(opt);      
        }      
        document.body.appendChild(temp);      
        temp.submit();      
        return temp;      
    }      
         
    


    t.jsp   往后台传递图片数据

    <%@ page language="java" contentType="text/html; charset=GBK"%>
    <%@ page import="javab.B" %> 
    
    <%
    String sDate = (String)request.getParameter("hid");
    String num = (String)request.getParameter("num");
    
    if(sDate==null)response.sendRedirect("index.jsp");
    else response.getWriter().write("shit:"+sDate);
    
    String rootUrl  = request.getRealPath("/");
    B b=new B();
    
    
    String log = b.start(sDate,rootUrl);
    
    sDate=null;
    
    //response.getWriter().write(""+num+" end");
    //response.sendRedirect("png.jsp?type=1");
    
    %>
    <script>
    window.onload=function(){
    	setTimeout('go()',500);
    }
     
    function go()
    {
    	var url = "png.jsp";
    	
    	post(url, {type :1});
    }
    
    function post(URL, PARAMS) {      
        var temp = document.createElement("form");      
        temp.action = URL;      
        temp.method = "post";      
        temp.style.display = "none";      
        for (var x in PARAMS) {      
            var opt = document.createElement("textarea");      
            opt.name = x;      
            opt.value = PARAMS[x];      
            // alert(opt.name)      
            temp.appendChild(opt);      
        }      
        document.body.appendChild(temp);      
        temp.submit();      
        return temp;      
    }
    </script>


    B.java  javabean文件 被t.jsp调用,负责解析base64图片数据,缩小到固定尺寸,并保存到后台

    package javab;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.util.ArrayList;
    import java.util.List;
    import javax.imageio.ImageIO;
    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;
    import java.util.Calendar;
    import java.awt.Image;
    import java.awt.image.AffineTransformOp;
    import java.awt.geom.AffineTransform;
    
    public class B {
    
    	int cnum = 0;
    	int pageNum = 0;
    	int posy = 0;
    	int posx = 0;
    	int smallw = 150;
    	int smallh = 200;
    	int pngNum = 24;//每页签名数
    
    	//WEB-INF/classes/绝对地址,根目录无法访问WEB-INF中资源,但WEB-INF中的java可以访问根目录,通过jsp把站点rootUrl传进来
    	//这里统一使用根目录地址,不在WEB-INF中放资源,只放javabean
    	String classRootUrl = "";
    	String fileName = "num.txt";//默认配置文件名
    	String unicode = "GBK";//生成文件默认编码格式
    	
    
    
    	//png64Data base64图片数据
    	//webUrl 网站根目录
    	public String start(String png64Data,String webUrl) throws Exception
    	{
    		String res = "ok";
    		
    		//1获取tomcat根目录
    		//classRootUrl = this.getClass().getClassLoader().getResource("").getPath()+"javab/";//获取tomcat class目录
    		classRootUrl = webUrl+"images/";//获取D:java	omcat7042webappshtml5Paint绝对地址,站点根目录
    		
    		//if(true)return res;
    
    
    		//2读取文档数字
    		//cnum = Integer.parseInt(this.readConfigFile().get(0));
    		cnum = R.getR().getNum(webUrl);
    		//7增加num
    		cnum = cnum + 1;
    
    		R.getR().write2File(String.valueOf(cnum));
    
    
    		//3根据数字算出位置,第几张签名墙,第几个位置
    		pageNum = (cnum-1)/pngNum;
    		posy = ((cnum-1)%pngNum)/4;
    		posx = ((cnum-1)%pngNum)%4;
    	
    		//4把用户绘制的base64数据转化成png
    		String bigPngUrl = classRootUrl+pageNum+".png";//签名墙名
    		String smallPngUrlt = classRootUrl+cnum+"t.png";//用户图名,原始临时图
    		String smallPngUrl = classRootUrl+cnum+".png";//用户图名,缩放后临时图
    		
    		if(!b642image(png64Data, smallPngUrlt))//创建用户图片,图片
    		{
    			//res = res+"step4 creat userpng fail ||";
    		}
    		//5缩放到约定好的尺寸
    		//new UploadImg("e://s.png", "e://", "ps_low1","png",30,30);
    		if(!pngScale(smallPngUrlt, classRootUrl,""+cnum,"png",smallw,smallh))
    		{
    			//res = res+"step5 scale fail ||";
    		}
    		//6把用户小图压缩(150*200)绘制到大图(600*1400)指定位置
    		//往大图绘制被去掉
    		
    		//8删除用户图
    		deleteFile(smallPngUrlt);
    		//deleteFile(smallPngUrl);
    		return res;
    	}
    	
    	/**
    	 * 导入两图片,把一张图画另一张上,然后保存为新图
    	 * @param bigPath
    	 * @param smallPath
    	 * @param newPath
    	 * @param x
    	 * @param y
    	 */
    	public final void overlapImage(String bigPath, String smallPath,String newPath,int x,int y) {
    		try {
    			BufferedImage big = ImageIO.read(new File(bigPath));
    			BufferedImage small = ImageIO.read(new File(smallPath));
    			Graphics2D g = big.createGraphics();
    			//g.drawImage(small, x, y, smallw, smallh, null);//这个方法导致透明图全黑
    			g.drawImage(small, x, y, small.getWidth(), small.getHeight(), null);
    			g.dispose();
    			ImageIO.write(big, "png", new File(newPath));
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    
    	public boolean pngScale(String fromFileStr, String saveToFileStr, String sysimgfile,String suffix,int width,int height) throws Exception {
    		// fileExtNmae是图片的格式 gif JPG 或png
    		// String fileExtNmae="";
    		double Ratio = 0.0;
    		File F = new File(fromFileStr);
    		if (!F.isFile())
    			throw new Exception(F
    					+ " is not image file error in CreateThumbnail!");
    		File ThF = new File(saveToFileStr, sysimgfile +"."+suffix);
    		BufferedImage Bi = ImageIO.read(F);
    		Image Itemp = Bi.getScaledInstance(width, height, Bi.SCALE_SMOOTH);
    		if ((Bi.getHeight() > width) || (Bi.getWidth() > height)) {
    			if (Bi.getHeight() > Bi.getWidth())
    				Ratio = (double)width / Bi.getHeight();
    			else
    				Ratio = (double)height / Bi.getWidth();
    		}
    		AffineTransformOp op = new AffineTransformOp(AffineTransform
    				.getScaleInstance(Ratio, Ratio), null);
    		Itemp = op.filter(Bi, null);
    		try {
    			ImageIO.write((BufferedImage) Itemp, suffix, ThF);
    		} catch (Exception ex) {
    			throw new Exception(" ImageIo.write error in CreatThum.: "
    					+ ex.getMessage());
    		}
    		return (true);
    	}
    
    	
    	/**
    	 * 将图片文件转化为字节数组字符串,并返回其Base64编码字符串
    	 * @param imgFilePath
    	 * @return
    	 */
    	public String getImageB64Str(String imgFilePath) {
    		byte[] data = null;
    
    		// 读取图片字节数组
    		try {
    			InputStream in = new FileInputStream(imgFilePath);
    			data = new byte[in.available()];
    			in.read(data);
    			in.close();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    
    		// 对字节数组Base64编码
    		BASE64Encoder encoder = new BASE64Encoder();
    		return encoder.encode(data);// 返回Base64编码过的字节数组字符串
    	}
    
    	/**
    	 * 对字节数组字符串进行Base64解码并生成图片
    	 * @param imgStr
    	 * @param imgFilePath
    	 * @return
    	 */
    	public boolean b642image(String imgStr, String imgFilePath) {// 
    		if (imgStr == null) // 图像数据为空
    			return false;
    		BASE64Decoder decoder = new BASE64Decoder();
    		try {
    			// Base64解码
    			byte[] bytes = decoder.decodeBuffer(imgStr);
    			for (int i = 0; i < bytes.length; ++i) {
    				if (bytes[i] < 0) {// 调整异常数据
    					bytes[i] += 256;
    				}
    			}
    			// 生成jpeg图片
    			OutputStream out = new FileOutputStream(imgFilePath);
    			out.write(bytes);
    			out.flush();
    			out.close();
    			return true;
    		} catch (Exception e) {
    			return false;
    		}
    	}
    	
    
    
    	public boolean deleteFile(String sPath) {
            boolean flag = false;
            File file = new File(sPath);
            // 路径为文件且不为空则进行删除
            if (file.isFile() && file.exists()) {
                file.delete();
                flag = true;
            }
            return flag;
        }
    
    
    	//检测文件是否被占用
    	public boolean bUse(String url)
    	{
    		File file=new File(url);
    		if(file.renameTo(file)){
    			return false;
    			//System.out.println("文件未被操作");
    		}else{
    			return true;
    			//System.out.println("文件正在被操作");
    		}
    	}
    }


    png.jsp  用户展示绘图结果

    <%@ page language="java" contentType="text/html; charset=GBK"%>
    <%@ page import="javab.R" %> 
    
    <%
    	//type=0是从开始页面跳转,type=1是从绘制并上传签名页面跳转
        String type = (String)request.getParameter("type");
    	int typeInt =0;
    	if(type==null)response.sendRedirect("index.jsp");
    	else typeInt = Integer.parseInt(type);
    
    	String root  = request.getRealPath("/");
    	R r = new R();
    	int userNum = r.getNum(root);
    	int pngNum = (userNum-1)/24+1;
    
    %>
    
    
    <html>
    <head>
    <title>标题</title>
    <style type="text/css">
    .d1 {
    	 100px;
    	height: 100px;
    	border: 0px solid #000;
    	position: fixed;
    	left: 0;
    	top:50%;
    	
    	margin-left: 0px;
    	margin-top: -100px;
    	_position: absolute;
    	_top: expression(eval(document.documentElement.clientHeight+document.documentElement.scrollTop;));
    	
    }
    
    .d2 {
    	 100px;
    	height: 100px;
    	border: 0px solid #000;
    	position: fixed;
    	right: 0;
    	
    	top:50%;
    	margin-left: 100px;
    	margin-top: -100px;
    	_position: absolute;
    	_top: expression(eval(document.documentElement.clientHeight+document.documentElement.scrollTop;));
    }
    
    .d3 {
    	 908px;
    	height: 109px;
    	border: 0px solid #000;
    	position: fixed;
    	left: 50%;
    	
    	bottom:1%;
    	margin-left: -454px;
    	margin-top: -109px;
    	_position: absolute;
    	_top: expression(eval(document.documentElement.clientHeight+document.documentElement.scrollTop;));
    	_left: expression(eval(document.documentElement.clientWidth/2+document.documentElement.scrollLeft;));
    }
    
    .pop {
    	 700px;
    	height: 406px;
    	border: 0px solid #000;
    	position: fixed;
    	left: 50%;
    	top: 8%;
    	
    	margin-left: -350px;
    	margin-top: -100px;
    	_position: absolute;
    	_top: expression(eval(document.documentElement.clientHeight+document.documentElement.scrollTop;));
    	_left: expression(eval(document.documentElement.clientWidth/2+document.documentElement.scrollLeft;));
    }
    
    </style>
    
    <script language =javascript > 
    
    var curIndex=0; 
    
    //document.location.reload();刷新页面
    
    window.onload=function(){
    
    	  
    
          var flag ='<%=typeInt%>';
    	  var len = '<%=pngNum%>'
    	  len = len -1;
    	  if(flag>0)//flag = 0是从初始界面跳转的,>0是从画图结束位置跳转过来的
    	  {
    
    	    //reurl();
    		curIndex = len;
    		//alert(curIndex);
    		changeBgImg();
    		changeButtonImg();
    	  }
    	  else
    	  {
    		 curIndex = 0;
    	  }
    }
    
    function reurl(){//刷新页面一次
       url = location.href; //把当前页面的地址赋给变量 url
       var times = url.split("&"); //分切变量 url 分隔符号为 "?"
       if(times[1] != 1){ //如果?后的值不等于1表示没有刷新
        url += "&1"; //把变量 url 的值加入 ?1
    
    	//alert(url);
        self.location.replace(url); //刷新页面
       }
    }
    
    function changeBgImg() 
    { 
    	var obj=document.getElementById("showpic"); 
    	
    	obj.src="../images/"+curIndex+"p.png"; 
    } 
    
    function changeButtonImg() 
    { 
    	var obj=document.getElementById("buttonpng"); 
    	obj.src="image/sharebutton.png"; 
    }
    
    
    function onClickLeft(event)
    {
    	if(curIndex>0)
    	{
    		curIndex-=1; 
    		//alert(curIndex);
    		changeBgImg();
    	}
    	
    
    }
    
    function onClickRight(event)
    {
    	if(document.getElementById("popBoard")){
    		document.body.removeChild(popBoard)
    	}
    
    	var len = '<%=pngNum%>';
    	//alert(len);
    	if(curIndex<(len-1))
    	{
    		curIndex+=1;
    		//alert(curIndex);
    		changeBgImg();
    	}
    }
    
    function onClickButton(event)
    {
    	if(document.getElementById("popBoard")){
    		document.body.removeChild(popBoard)
    	}
    
    	var flag = '<%=typeInt%>';
    
    	if(flag>0)//我要分享分享
    	{
    		//弹出div nafio temp
    		//alert('share');
    		pop(event);
    	}
    	else//我要签名
    	{
    		var url = "paint.html";
    		window.open(url)
    	}
    	
    }
    
    function onClickBg(event)
    {
    	if(document.getElementById("popBoard")){
    		document.body.removeChild(popBoard)
    	}
    }
    
    
    function pop(e){
    
     if(document.getElementById("popBoard")){
      document.body.removeChild(popBoard)
      return;
     }
     e=e||event;
    
     var popImg = document.createElement("img");
     popImg.setAttribute("src","image/share.png");
    
     //colorClose.onclick=function(){document.body.removeChild(colorBoard)};
    
     var popBoard = document.createElement("div");
     popBoard.id="popBoard";
     popBoard.setAttribute("class","pop");
     popBoard.appendChild(popImg);
     document.body.appendChild(popBoard);
    
    }
    
    
    
    </script> 
    
    </head>
    <center>
    <body>
    
     <!-- 左按键 -->
     <div class = "d1" onclick="onClickLeft(event)">
     <img src="image/lb.png"/> 
     </div>
    
     <!-- 图片浏览区 -->
     <div>
      <img src="../images/0p.png" id="showpic" onclick="onClickBg(event)"/> 
     </div>
    
     <!-- 右按键 -->
     <div class = "d2" onclick="onClickRight(event)">
     <img src="image/rb.png"/> 
     </div>
    
    <!-- 下按钮 -->
     <div class = "d3" onclick="onClickButton(event)">
    	<img src="image/btmbutton.png" id="buttonpng"></img>
     </div>
    
    </body>
    </center>
    </html>


    H.java  独立在后台运行,负责处理用户上传的小图,并把小图按位置绘制到大图

    package javab;
    
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.nio.channels.FileChannel;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.imageio.ImageIO;
    
    public class H implements Runnable{
    
    	public static int bigNum = 1;//bigNum = 1时有10张图,2时有20张墙
    	
    	public int lastNum = 0;
    	public int cnum = 0;
    	
    	//public String classRootUrl = "C:/soft/tomcat7054/webapps/r/";
    	static public String classRootUrl = "D:/java/tomcat7042/webapps/html5Paint/";
    	static public String imgUrl = classRootUrl+"images/";
    	
    	static int smallw = 150;
    	static int smallh = 200;
    	static int pageNum = 24;//每页图片数
    
    	public static void main(String[] args) {
    
    		H h = new H();
    
    		h.lastNum = R.getR().getNum(classRootUrl);
    		
    		//每秒
    		new Thread(h).start();//画图线程
    
    
    	}
    
    	
    	
    	@Override
    	public void run() {
    
    		while(true)
    		{
    			
    				cnum = R.getR().getNum(classRootUrl);
    			
    				if(cnum>lastNum)
    				{
    					System.out.println("newUser come cnum:"+cnum+" lastNum:"+lastNum);
    					
    					//循环新图到大图
    					int len = cnum-lastNum;
    					for(int i=0;i<len;i++)
    					{
    						int smallID = lastNum+1+i;//要画的小图的id,小图id从1开始,cnum代表当前,而不是之前
    
    						int bigID = (smallID-1)/pageNum;//小图要画在那张大图上(大图id)
    
    						String bigPngUrl = imgUrl+bigID+"p.png";
    
    						String smallPngUrl =imgUrl+smallID+".png";
    
    						int count = 0;//nafio
    						while(true)
    						{
    							File f = new File(smallPngUrl);
    							if( !f.exists())
    							{
    								//System.out.println(""+smallPngUrl+"not exists");
    								count++;//nafio
    							}
    							else if (!f.renameTo(f))
    							{
    								//System.out.println(""+smallPngUrl+"be use");
    							}
    							else if(!new File(bigPngUrl).exists())
    							{
    								System.out.println("---"+bigPngUrl+"not exists");
    							}
    							else 
    							{
    								count = 0;//nafio
    								break;
    							}
    
    							if(count>100)break;//nafio
    							try
    							{
    								Thread.sleep(100);
    							}
    							catch (Exception e)
    							{
    								e.printStackTrace();
    							}
    							
    						}
    
    						if(count>100)
    						{
    							System.out.println(""+smallPngUrl+"not exists");
    							continue;//nafio
    						}
    
    						int posx = ((smallID-1)%pageNum)%4;
    
    						int posy = ((smallID-1)%pageNum)/4;
    
    						overlapImage(bigPngUrl, smallPngUrl , bigPngUrl,posx*smallw,posy*smallh);
    
    					}
    					lastNum = cnum;
    				}
    				
    			
    		}
    	}
    
    
    	/**
    	 * 导入两图片,把一张图画另一张上,然后保存为新图
    	 * @param bigPath
    	 * @param smallPath
    	 * @param newPath
    	 * @param x
    	 * @param y
    	 */
    	public final void overlapImage(String bigPath, String smallPath,String newPath,int x,int y) {
    		try {
    			BufferedImage big = ImageIO.read(new File(bigPath));
    			BufferedImage small = ImageIO.read(new File(smallPath));
    			Graphics2D g = big.createGraphics();
    			//g.drawImage(small, x, y, smallw, smallh, null);//这个方法导致透明图全黑
    			g.drawImage(small, x, y, small.getWidth(), small.getHeight(), null);
    			g.dispose();
    			ImageIO.write(big, "png", new File(newPath));
    		} catch (Exception e) {
    			System.out.println("big:"+bigPath+" small:"+smallPath+" new:"+newPath);
    			e.printStackTrace();
    		}
    	}
    
    
    }
    



  • 相关阅读:
    将后台返回的 xml replace
    程序员数学的重要性
    .net里生成的 checkboxlist 至少要选择一个
    关于如何坚持目标,网上偶然看到的,转载一下
    犹豫不决(收集)
    CSS中Padding参数说明及使用指南
    IE地址栏小图标问题
    常用sql语句集锦
    ie9怎么开兼容模式
    一台MySql服务器不同数据库之间数据同步_解决方案(Java)
  • 原文地址:https://www.cnblogs.com/nafio/p/9137635.html
Copyright © 2020-2023  润新知