JS 下载图片
function getimg() //另存为存放在服务器上图片到本地的方法
{
event.returnValue = false;
show.window.location.href = imgSrc.src; //$("#winShowPhoto > img")[0].src;
timer = setInterval(checkload, 100)
}
function checkload()
{
if (show.readyState != "complete")
{
//调用document.execCommand方法,'Saveas'表示打开文件另存为对话框命令只有IE试用
show.document.execCommand('Saveas');
clearInterval(timer)
}
}
function Download()
{
//cavas 保存图片到本地 js 实现
//------------------------------------------------------------------------
//1.确定图片的类型 获取到的图片格式 data:image/Png;base64,......
var type = 'png';//你想要什么图片格式 就选什么吧
var d = document.getElementById("imgSrc");
//$("#winShowPhoto > canvas")// currentSrc$("#winShowPhoto > img")[0]
var imgdata = d.toDataURL(type);
//2.0 将mime-type改为image/octet-stream,强制让浏览器下载
var fixtype = function (type)
{
type = type.toLocaleLowerCase().replace(/jpg/i, 'jpeg');
var r = type.match(/png|jpeg|bmp|gif/)[0];
return 'image/' + r;
};
imgdata = imgdata.replace(fixtype(type), 'image/octet-stream');
//3.0 将图片保存到本地
var savaFile = function (data, filename)
{
var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
save_link.href = data;
save_link.download = filename;
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
save_link.dispatchEvent(event);
};
var filename = '' + new Date().getSeconds() + '.' + type;
//我想用当前秒是可以解决重名的问题了 不行你就换成毫秒
savaFile(imgdata, filename);
};
/**
* 根据图片生成画布
*/
function convertImageToCanvas(image)
{
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0);
return canvas;
}
/**
* 下载图片
*/
function down()
{
var sampleImage = $("#winShowPhoto > img")[0];// document.getElementById("imgSrc"),
canvas = convertImageToCanvas(sampleImage);
url = canvas.toDataURL("image/png");//PNG格式
//以下代码为下载此图片功能
var triggerDownload = $("#tttt").attr("href", url).attr("download", "order-1111111111.png");
triggerDownload[0].click();
// triggerDownload.remove();
}