下载图片
转载:https://blog.csdn.net/weixin_33331978/article/details/112929048
流文件
const axios = require('axios')
const fs = require('fs')
let url = 'https://gss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/314e251f95cad1c83f06dc11733e6709c93d5142.jpg'
axios({
url,
responseType: 'stream'
}).then(
(resp) => {
const writer = fs.createWriteStream('./t2.jpg')
resp.data.pipe(writer)
writer.on('finish', () => {
console.log('finish')
})
writer.on('error', () => {
console.log('error')
})
}
)
arraybuffer 二进制文件
const axios = require('axios')
const fs = require('fs')
let url = 'https://gss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/314e251f95cad1c83f06dc11733e6709c93d5142.jpg'
axios({
url,
responseType: 'arraybuffer'
}).then(
({data}) => {
fs.writeFileSync('./t.jpg', data, 'binary')
}
)
生成图片
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
// 加载龙的图片
let img = new Image();
img.crossOrigin = "";
img.src = "http://127.0.0.1:3000/";
img.onload = () => {
console.log(img.width);
// 把图片绘制到canvas里
const draw = () => {
const canvas = document.createElement("canvas");
canvas.width = img.width || 300;
canvas.height = img.height;
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
// 获取像素数据
const imgData = ctx.getImageData(0, 0, img.width, img.height).data;
// 拼接字符
join(imgData);
};
draw();
};
// 把像素数据拼接成字符
const join = (data) => {
let gap = 10;
let str = "";
for (let h = 0; h < img.height; h += gap) {
str += "\n";
for (let w = 0; w < img.width; w += gap) {
str += " "; // 因为字符的高度普遍都比其宽度大,所以额外添加一个空字符平衡一下,否则最终的图形会感觉被拉高了
let pos = (h * img.width + w) * 4;
let r = data[pos];
let g = data[pos + 1];
let b = data[pos + 2];
// rgb转换成yuv格式,根据y(亮度)来判断显示什么字符
let y = r * 0.299 + g * 0.578 + b * 0.114;
if (y >= 190) {
// 浅色
str += " ";
} else {
// 深色
str += "#";
}
}
}
console.log(str);
};
</script>
</body>
</html>
// https://www.degraeve.com/img2txt.php。
var http = require("http");
//文件处理
var fs = require("fs");
// req 路由监听空 res 上下文函数
var server = http.createServer((req, res) => {
// 公共请求头
res.writeHead(200, {
// "Content-Type": "text/html;chaset=UTF-8",
'Content-Type': 'image/png',
//设置允许跨域的域名,*代表允许任意域名跨域
"Access-Control-Allow-Origin": "*",
});
// 路由监控
if (req.url == "/fang") {
res.end("fang");
} else if (req.url == "/yuan") {
res.end("yuan");
} else {
// res.end("404");
// res.end("<a href='/fang'>fang</a><br><a href='yuan'>yuan</a>");
// fs.readFile(path,’binary’, function (err, file) { })的参数多了一个’binary’,以二进制流的方式读取。
// res.write(file,’binary’); response也以二进制流的方式向浏览器输出。
fs.readFile('./1.png', 'binary', function (err, file) {
if (err) {
console.log(err);
return;
} else {
res.write(file, 'binary');
res.end();
}
});
}
});
server.listen(3000, "127.0.0.1", (res) => {
console.log("http://127.0.0.1:3000/");
});
参考:https://www.cnblogs.com/fanbi/p/8479745.html
原生
var http = require('http');
var fs = require('fs');
var url = require('url');
// 创建服务器
http.createServer( function (request, response) {
// 解析请求,包括文件名
var pathname = url.parse(request.url).pathname;
// 输出请求的文件名
console.log("Request for " + pathname + " received.");
// 从文件系统中读取请求的文件内容
fs.readFile(pathname.substr(1), function (err, data) {
var urlContent = pathname.substr(1);
if(urlContent.lastIndexOf("png") > -1){
if (err) {
console.log(err);
// HTTP 状态码: 404 : NOT FOUND
// Content Type: text/plain
response.writeHead(404, {'Content-Type': 'text/html'});
}else{
// HTTP 状态码: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'image/png'});
var imageFilePath = pathname.substr(1);
var stream = fs.createReadStream( imageFilePath );
var responseData = [];//存储文件流
if (stream) {//判断状态
stream.on( 'data', function( chunk ) {
responseData.push( chunk );
});
stream.on( 'end', function() {
var finalData = Buffer.concat( responseData );
response.write( finalData );
response.end();
});
}
}
}else if(urlContent.lastIndexOf("html") > -1){
if (err) {
console.log(err);
// HTTP 状态码: 404 : NOT FOUND
// Content Type: text/plain
response.writeHead(404, {'Content-Type': 'text/html'});
}else{
// HTTP 状态码: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/html'});
// 响应文件内容
response.write(data.toString());
}
// 发送响应数据
response.end();
}else{
console.log("unSupport Type, Please contact Administrator err url="+urlContent);
}
});
}).listen(80);
2.2 用Express框架版本
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/public/images/*', function (req, res) {
res.sendFile( __dirname + "/" + req.url );
console.log("Request for " + req.url + " received.");
})
app.get('/public/html/index.html', function (req, res) {
res.sendFile( __dirname + "/" + "/public/html/index.html" );
console.log("Request for " + req.url + " received.");
})
//如果访问网页和本地同名,可以使用以下版本
app.get('/public/html/*.html', function (req, res) {
res.sendFile( __dirname + "/" + req.url );
console.log("Request for " + req.url + " received.");
})
app.get('/public/register', function (req, res) {
res.sendFile( __dirname + "/" + "/public/html/register.html" );
console.log("Request for " + req.url + " received.");
})
var server = app.listen(80, function () {
console.log('Server running at http://127.0.0.1:80/');
})