日期:2014-05-16  浏览次数:20661 次

html2canvas 截屏后上传到服务器端(springmvc3)
利用html2canvas截屏后可以生成base64类型的图片,但是这样的图片很明显不能被引用或者被SNS工具来分享。这样就必须截屏后再上传数据到后台服务器端重新保存。

前端js代码:

 $("#saveImage").click(function() {
					html2canvas($('#mypics'), {
						onrendered : function(canvas) {
							var myImage = canvas.toDataURL("image/jpeg");
							//并将图片上传到服务器用作图片分享
							$.ajax({
								type : "POST",
								url : '${ctx}/qsupload',
								data : {data:myImage},
								timeout : 60000,
								success : function(data){
									$('#myShowImage').attr('src', '${ctxStatic}/usertemp/'+data+'.jpg'); //服务器上保存图片路径,data是返回的文件名。
								}
							});
						}
					});
				});


后端代码


import org.apache.commons.codec.binary.Base64;

@RequestMapping(value = { "${frontPath}/qsupload" }, method = { RequestMethod.POST })
	@ResponseBody
	public String petUpgradeTarget(HttpServletRequest request, String data) {
		String serverPath = request.getSession().getServletContext()
				.getRealPath("/");
		Base64 base64 = new Base64();
		try {

      //注意点:实际的图片数据是从 data:image/jpeg;base64, 后开始的
			byte[] k = base64.decode(data.substring("data:image/jpeg;base64,"
					.length()));
			InputStream is = new ByteArrayInputStream(k);
			String fileName = UUID.randomUUID().toString();
			String imgFilePath = serverPath + "\\static\\usertemp\\" + fileName + ".jpg";

                       //以下其实可以忽略,将图片压缩处理了一下,可以小一点

			double ratio = 1.0;
			BufferedImage image = ImageIO.read(is);
			int newWidth = (int) (image.getWidth() * ratio);
			int newHeight = (int) (image.getHeight() * ratio);
			Image newimage = image.getScaledInstance(newWidth, newHeight,
			Image.SCALE_SMOOTH);
			BufferedImage tag = new BufferedImage(newWidth, newHeight,
					BufferedImage.TYPE_INT_RGB);
			Graphics g = tag.getGraphics();
			g.drawImage(newimage, 0, 0, null);
			g.dispose();
			ImageIO.write(tag, "jpg", new File(imgFilePath));
			return fileName;
		} catch (Exception e) {
			return "error";
		}
	}