asp 最初没有图片处理方法,所以需要借助 aspjpeg 等第三方组件来处理图片。但目前大多数服务器都是 Server 2012 及以上版本了,这些服务器内置 IE10甚至 IE11等浏览器,所以,我们完全可以利用IE9+浏览器的特性,实现 canvas 图片处理。代码如下[文件名:scaleImg.asp ]:
<%@ Language= "VBScript" %><%
Response.ContentType = "image/jpeg"
Response.BinaryWrite scaleImage("test.jpg", 200, 200)
function scaleImage(src, w, h)
set img = GD()
scaleImage = img.scaleImage(src, w, h)
' img.save(scaleImage, "home.scaled.png")
end function
%><script language="javascript" runat="server">
function GD() {
var me = new Object;
me.newImg = function(src) {
stm.type = 1; stm.open();
stm.loadFromFile(getPath(src));
var bin = stm.read(); stm.close();
root.nodeTypedValue = bin;
var img = new doc.frames.Image, isLoad = false;
img.setAttribute("crossOrigin", "anonymous");
img.onload = img.onerror = function() { isLoad = true; };
img.src = "data:image/jpeg;base64," + root.text;
// 需要异步等待 img 呈现图片
var xhr = new ActiveXObject("MsXml2.ServerXmlHttp");
while(!isLoad) {
xhr.open("HEAD", "http://localhost/web.config", true);
xhr.send(); xhr.waitForResponse(1);
}
return img;
};
me.scaleImage = function(src, w, h, q) {
if(!w && !h) return Infinity;
var img = this.newImg(src);
// 不存在宽度设置,则限定高度,宽度自适应
if(!w) w = img.width * h / img.height;
if(!h) h = img.height * w / img.width;
cvs.width = w; cvs.height = h;
var ss = img.width / img.height, ts = w / h;
// 对比原宽高比和现在的宽高比,前者大于后者,基于高度裁剪,否则基于宽度裁剪
var scale = ss > ts ? img.height / h : img.width / w; // 计算缩放比
var sx = (img.width - w * scale) / 2;
var sy = (img.height - h * scale) / 2;
if(img.width) ctx.drawImage(img, sx, sy, w * scale, h * scale, 0, 0, w, h);
// 当服务器支持 IE 11 时,才可以保存 jpg 格式并指定保存质量,默认为 png
root.text = cvs.toDataURL("image/jpeg", q || 0.6).slice(23);
return root.nodeTypedValue;
};
me.save = function(bin, path) {
stm.open(); stm.write(bin);
stm.saveToFile(getPath(path), 2);
stm.close();
};
// 判断是否 ASP 环境
var getPath = function(path) { return "Server" in this ? Server.MapPath(path) : path; };
var stm = new ActiveXObject("Adodb.Stream");
var doc = new ActiveXObject("htmlfile");
var xml = doc.createElement("xml");
xml.loadXML("<x/>");
var root = xml.documentElement;
root.dataType = "bin.base64";
// 启动 IE9+ 模式
doc.write("<meta http-equiv='X-UA-Compatible' content='IE=edge' />");
// 创建画布
var cvs = doc.createElement("canvas");
var ctx = cvs.getContext("2d");
return me;
}
</script>