一 。前台加载跨域图片
//封装的方法获取图片长宽
var imgReady = (function () {
var list = [], intervalId = null,
// 用来执行队列
tick = function () {
var i = 0;
for (; i < list.length; i++) {
list[i].end ? list.splice(i--, 1) : list[i]();
};
!list.length && stop();
},
// 停止所有定时器队列
stop = function () {
clearInterval(intervalId);
intervalId = null;
};
return function (url, ready, load, error) {
var onready, width, height, newWidth, newHeight,
img = new Image();
img.src = url;
// 如果图片被缓存,则直接返回缓存数据
if (img.complete) {
ready.call(img);
load && load.call(img);
return;
};
width = img.width;
height = img.height;
// 加载错误后的事件
img.onerror = function () {
error && error.call(img);
onready.end = true;
img = img.onload = img.onerror = null;
};
// 图片尺寸就绪
onready = function () {
newWidth = img.width;
newHeight = img.height;
if (newWidth !== width || newHeight !== height ||newWidth * newHeight > 1024) {
// 如果图片已经在其他地方加载可使用面积检测
ready.call(img);
onready.end = true;
};
};
onready();
// 完全加载完毕的事件
img.onload = function () {
// onload在定时器时间差范围内可能比onready快
// 这里进行检查并保证onready优先执行
!onready.end && onready();
load && load.call(img);
// IE gif动画会循环执行onload,置空onload即可
img = img.onload = img.onerror = null;
};
// 加入队列中定期执行
if (!onready.end) {
list.push(onready);
// 无论何时只允许出现一个定时器,减少浏览器性能损耗
if (intervalId === null) intervalId = setInterval(tick, 40);
};
};
})();
//加载跨域图片
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var myCanvas_rect = canvas.getBoundingClientRect();
var canvasWidth = myCanvas_rect.width;
console.log(canvasWidth);
var img = new Image();
img.src = obj;
//图片加载完后,将其显示在canvas中
img.onload = function(){
context.drawImage(this, 0, 0,canvasWidth,this.height*(canvasWidth/this.width));
// context.drawImage(this, 0, 0, 1080, 980)改变图片大小到1080*980
}
//canvas设置
var mapping = function(width,height,img){
console.log(img);
//获取页面尺寸
/* while(width>1300||height>600){
width=width/2;
height = height/2
}*/
var canvasHistory = [];
var step = -1;
var myCanvas = document.getElementById('canvas');
var myCanvas_rect = myCanvas.getBoundingClientRect();
var canvasWidth = myCanvas_rect.width;
var canvasHeight = height;
//声明canvas
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
//设置canvas尺寸
canvas.width = canvasWidth * 0.98;
canvas.height = height*(canvasWidth/width);
//画笔颜色
var strokeColor = "red";
//鼠标
isMouseDown = false;
//上一次绘制的的坐标
var lastLoc = {x:0,y:0};
//初始记录事件
var lastTimestamp = 0;
//上一次线条宽度
var lastLineWidth = -1;
//var
var maxV = 10;
var minV = 0.1;
var maxLineWidth = 2;
var minLineWidth = 1;
context.fillStyle = 'rgba(255, 255, 255, 0)'
//清除
$('#clear_btn').on('click',function (e){
context.clearRect( 0, 0, canvasWidth,canvasHeight);
})
$('#save').on('click',function (e){
context.clearRect( 0, 0, canvasWidth,canvasHeight);
})
//获取canvas 坐标 x,y 分别代表相对window内的xy
function windowToCanvas(x,y){
//canvas提供的方法返回canvas 距 他外围包围盒子的距离left,top值
var bbox = canvas.getBoundingClientRect();
//返回的就是canvas 内的坐标值
return {x : Math.round(x - bbox.left),y : Math.round(y - bbox.top)}
}
//封装 事件
function beginStroke(point){
isMouseDown = true;
//第一次用户画的坐标初始值
lastLoc = windowToCanvas(point.x,point.y);
//获取首次点击鼠标 事件戳
lastTimestamp = new Date().getTime();
}
function endStroke(){
isMouseDown = false;
}
function moveStroke(point){
//开始绘制直线
var curLoc = windowToCanvas(point.x , point.y);
//路程
var s = calcDistance( curLoc, lastLoc);
//结束时间
var curTimestamp = new Date().getTime();
//时间差
var t = curTimestamp - lastTimestamp;
//绘制线条粗细
var lineWidth = calcLineWidth(t,s);
//绘制
context.beginPath();
context.moveTo(lastLoc.x ,lastLoc.y);
context.lineTo(curLoc.x , curLoc.y);
context.strokeStyle = strokeColor;
context.lineWidth = lineWidth;
context.lineCap = "round";
context.lineJoin = "round";
context.stroke();
//给lastLoc赋值维护
lastLoc = curLoc;
//时间更新
lastTimestamp = curTimestamp;
lastLineWidth = lineWidth;
}
// 撤销方法
$scope.canvasUndo = function() {
if (step >= 0) {
step--;
context.clearRect(0, 0, canvasWidth, canvasHeight);
var canvasPic = new Image();
console.log(step);
canvasPic.src = canvasHistory[step];
canvasPic.addEventListener('load', () => {
context.drawImage(canvasPic, 0, 0);
});
} else {
console.log('不能再继续撤销了');
}
}
// 清除方法
$scope.del = function() {
context.clearRect(0, 0, canvasWidth, canvasHeight);
var canvasPic = new Image();
step='-1';
canvasPic.src = canvasHistory[step];
canvasPic.addEventListener('load', () => {
context.drawImage(canvasPic, 0, 0);
});
}
//pc鼠标事件
canvas.onmousedown = function(e){
step++;
if (step < canvasHistory.length) {
canvasHistory.length = step; // 截断数组
}
e.preventDefault();
beginStroke({x:e.clientX , y:e.clientY});
}
canvas.onmouseup = function(e){
e.preventDefault();
endStroke();
canvasHistory.push(canvas.toDataURL());
console.log(canvasHistory);
}
canvas.onmouseout = function(e){
e.preventDefault();
endStroke();
}
canvas.onmousemove = function(e){
e.preventDefault();
if(isMouseDown){
moveStroke({x:e.clientX , y:e.clientY});
}
}
//速度 = 路程 / 时间 用来计算书写速度来改变线条粗细
function calcDistance (loc1,loc2){
//返回 数的平方根
return Math.sqrt((loc1.x - loc2.x) * (loc1.x - loc2.x) + (loc1.y - loc2.y) * (loc1.y - loc2.y) );
}
//线条宽度
function calcLineWidth(t,s){
var v = s/t;
var resultLineWidth;
if(v <= minV){
resultLineWidth = maxLineWidth;
}else if(v >= maxV){
resultLineWidth = minLineWidth;
}else{
resultLineWidth = maxLineWidth - (v-minV)/(maxV-minV)*(maxLineWidth-minLineWidth);
}
if( lastLineWidth == -1){
return resultLineWidth;
}else{
return resultLineWidth;
}
}
}
二 后台下载图片并调用上传
//文件上传
public static String uploadFile(String url, File file) throws ClientProtocolException, IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse httpResponse = null;
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
//multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
//File file = new File("F:\\Ken\\1.PNG");
//FileBody bin = new FileBody(file);
//multipartEntityBuilder.addBinaryBody("file", file,ContentType.create("image/png"),"abc.pdf");
//当设置了setSocketTimeout参数后,以下代码上传PDF不能成功,将setSocketTimeout参数去掉后此可以上传成功。上传图片则没有个限制
//multipartEntityBuilder.addBinaryBody("file",file,ContentType.create("application/octet-stream"),"abd.pdf");
multipartEntityBuilder.addBinaryBody("file", file);
//multipartEntityBuilder.addPart("comment", new StringBody("This is comment", ContentType.TEXT_PLAIN));
multipartEntityBuilder.addTextBody("comment", "this is comment");
HttpEntity httpEntity = multipartEntityBuilder.build();
httpPost.setEntity(httpEntity);
httpResponse = httpClient.execute(httpPost);
HttpEntity responseEntity = httpResponse.getEntity();
int statusCode = httpResponse.getStatusLine().getStatusCode();
System.out.println(statusCode);
if (statusCode == 200) {
BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
StringBuffer buffer = new StringBuffer();
String str = "";
while (!StringUtils.isEmpty(str = reader.readLine())) {
buffer.append(str);
}
System.out.println(buffer.toString());
return buffer.toString();
}
httpClient.close();
if (httpResponse != null) {
httpResponse.close();
}
return statusCode;
}
下载 加载图片
//解析base64码,获取图片格式
String str [] = imgStr.split(",");
imgStr = str[1];
String imgInfo = str[0];
String imgExt = imgInfo.split("/")[1].split(";")[0];
BASE64Decoder decoder = new BASE64Decoder();
//Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for(int i=0;i<b.length;++i)
{
if(b[i]<0)
{//调整异常数据
b[i]+=256;
}
}
String imgFilePath = ""; //新生成的图片
String imgFilePathSmall = "";
imgFilePath = "D:\\1."+imgExt;
/*if (getCurrentOS().equals("Linux")) {
imgFilePath = TMP_PATH+"/"+pk+"."+imgExt;
}else {
imgFilePath = TMP_PATH + pk +"."+imgExt;
}*/
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
File file = new File("D:\\1."+imgExt);