我如何从node.js尖锐模块缓冲区访问图像 [英] How do i access an image from the node.js sharp module buffer

查看:92
本文介绍了我如何从node.js尖锐模块缓冲区访问图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是node.js和Web开发的新手,并且对node.js Sharp模块有疑问.我想使用node.js sharp模块调整图像大小/裁剪图像,将其存储到缓冲区中,然后再访问它. 阅读 Sharp API 之后,我想到了这个代码示例.

I'm new to node.js and web development and have a question regarding the node.js sharp module. I want to resize/crop an image using the node.js sharp module, store it to a buffer and access it afterwards. After reading the Sharp API I came up with this code example.

sharp('img.jpg').extract(extract).resize(height, width).toBuffer(function (err, data, info) {img = data;});

我认为变量img现在包含我的新图像. 我的第一个问题是我的假设是否正确. 如果正确,我如何在我的网站上显示新图像?如果可能的话,我想使用HTML img标签.但是,如果有更好和更轻松的方法,请随时告诉我.我不想将图像存储到本地文件.

I thought that the variable img now contains my new image. My first question would be whether my assumption is correct. If this is correct, how can i display the new image on my website? If possible, I would like to use an HTML img tag. But if there are better and easier ways, feel free to let me know. I don't want to store the image to a local file.

感谢您的帮助!

推荐答案

是正确的.首先,您需要使用fs将映像保存在磁盘上,例如->

That's correct. You first need to save your image on your disk with fs for example ->

const   saveImageOnDisk = (base64Image, imageName) => 
{
    const   buf = new Buffer(base64Image.replace(/^data:image\/\w+;base64,/, ''), 'base64');

    fs.writeFile(`./${imageName}.png`, buf, {encoding: 'base64', flag: 'w'}, err => console.warn(err));
};

然后,您可以尝试通过对Sharp进行一些操作(例如在节点服务器上显示该图像)来访问该图像

And then, you can try to access this image by doing some operation with Sharp (ex. on a node server to display the image)

exports.getImage = (req, res) =>
{
    const   fileName = `./${req.params.image}`;
    const   width = 200;
    const   height = 200;

    sharp(fileName)
    .resize(height, width)
    .toBuffer()
    .then((data) =>
    {
        //To display the image
        res.writeHead(200, {
            'Content-Type': 'image/png',
            'Content-Length': data.length
        });
        return (res.end(data));
    })
    .catch(err => console.log(err));
};

所以,用这样的路线

app.route('/myImages/:image').get(Methods.getImage);

您可以使用简单的URL访问图像-> http://yourserver.xyz/myImages/imageX

You can access your image with you simple url -> http://yourserver.xyz/myImages/imageX

这篇关于我如何从node.js尖锐模块缓冲区访问图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆