node.js 上传图片
依赖库 connect,gm,imagemagick,image-size
connect:中间件
gm,imagemagick:用来处理图片如缩放、切割、添加文字水印等
image-szie:获取图片的宽高
图片上传处理服务,保存server.js
var http = require("http");
var connect = require("connect");
var url = require("url");
var fs = require("fs");
var imagesize = require("image-size");
var gm = require("gm");
var imageMagick = gm.subClass({imageMagick: true});
var oldImgName;
var app = connect().use(function(req, res, next){
var list = [];
var len = 0;
var pathName = url.parse(req.url).pathname;
pathName = pathName.substring(1, pathName.length);
oldImgName = req.headers.imgname;
req.on("error", function(err){
console.log(err);
});
req.on("data", function(chunk){
list.push(chunk);
len += chunk.length;
});
req.on("end", function(){
var buf = Buffer.concat(list, len);
req.data = {"path": pathName, "buf": buf};
next();
});
}).use(function(req, res, next){
if(req.data.path === "upload" && oldImgName){
fs.writeFileSync("./img/new_"+oldImgName, req.data.buf);
//取图片宽高
var imageInfo = imagesize("./img/new_"+oldImgName);
console.log(imageInfo.width, imageInfo.height);
//打印水印
var imgM = imageMagick("./img/new_"+oldImgName);
imgM.fill("blue");
imgM.fontSize(30);
imgM.drawText(100, 100, Date.now().toString());
imgM.write("./img/new_"+oldImgName, function(err){
if(err){
console.log(err);
}
});
//图片切割
var imgM2 = imageMagick("./img/new_"+oldImgName);
imgM2.crop(300, 300, 0, 0);//做切割
imgM2.write("./img/new_mid_"+oldImgName, function(err){
if(err){
console.log(err);
}
});
fs.writeFileSync("./img/new_min_"+oldImgName, req.data.buf);
var imgM_min = imageMagick("./img/new_min_"+oldImgName);
//imgM_min(“img.png”).crop(width, height, x, y)//做切割
//!=强制缩放
imgM_min.resize(200, 200, "!").autoOrient().write("./img/new_min_"+oldImgName, function(err){
if(err){
console.log(err);
}
});
}
next();
}).use(function(req, res){
res.writeHead(200, {"Content-Type": "text/plain; charset=UTF-8"});
res.write("ending");
res.end();
});
http.createServer(app).listen(7650);
console.log("start....." + 7650);
客户端请求保存代码test.js
var http = require("http");
var fs = require("fs");
var imgPath = "./12306.jpg";
var data = fs.readFileSync(imgPath);
var options = {
"hostname": "127.0.0.1",
"port":7650,
"path":"/upload",
"method":"post",
"headers":{
"Content-Type":"application/octet-stream",
"imgName":"12306.jpg"
}
};
var req = http.request(options, function(res){
res.on(‘data‘, function (chunk){
if(res.statusCode != 200){
console.log("reqest error");
}else{
console.log(chunk.toString());
}
});
});
req.write(data);
req.end();
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。