[英]How do I convert an image to a base64-encoded data URL in sails.js or generally in the servers side JavaScript?
I am making a small app in sails.js
and I need to store images in database.我正在
sails.js
制作一个小应用程序,我需要将图像存储在数据库中。 For that, I need to convert an image to a base64-encoded data URL so that I can save it as a string in my sails models.为此,我需要将图像转换为 base64 编码的数据 URL,以便我可以将其保存为我的帆模型中的字符串。 However, I don't know how to convert it in this form.
但是,我不知道如何将其转换为这种形式。 All the older questions asked about converting an image to base64-encoded data URLs, and they answer this about doing it on the client side.
所有关于将图像转换为 base64 编码的数据 URL 的较旧问题都被问到,他们回答了关于在客户端执行此操作的问题。 However, I want to do it on the server side while I will be getting the image through a post request.
但是,我想在服务器端执行此操作,同时我将通过发布请求获取图像。 How can I achieve this?
我怎样才能做到这一点?
As I understand you want to convert a file into base64 encoded string.据我了解,您想将文件转换为 base64 编码的字符串。 Whether the file is image or not, that does not matter.
文件是否是图像,这无关紧要。
var fs = require('fs');
// function to encode file data to base64 encoded string
function base64_encode(file) {
// read binary data
var bitmap = fs.readFileSync(file);
// convert binary data to base64 encoded string
return new Buffer(bitmap).toString('base64');
}
Usage:用法:
var base64str = base64_encode('kitten.jpg');
It can be achieved with readFileSync , passing in the image path as the first parameter and an encoding option as the second.它可以通过readFileSync实现,将图像路径作为第一个参数传递,将编码选项作为第二个参数传递。 As show below:
如下图所示:
var fs = require('fs');
var imageAsBase64 = fs.readFileSync('./your-image.png', 'base64');
As per the node documentation:根据 节点文档:
fs.readFileSync(path[, options])
fs.readFileSync(path[, options])
Synchronous version of fs.readFile().
fs.readFile() 的同步版本。 Returns the contents of the path.
返回路径的内容。
If the encoding option is specified then this function returns a string.
如果指定了编码选项,则此函数返回一个字符串。 Otherwise it returns a buffer.
否则它返回一个缓冲区。
//You can use the image-to-base64 //可以使用image-to-base64
const imageToBase64 = require('image-to-base64');
imageToBase64("URL") // insert image url here.
.then( (response) => {
console.log(response); // the response will be the string base64.
}
)
.catch(
(error) => {
console.log(error);
}
)
//instala via npm
npm install --save image-to-uri
//declara no codigo
const imageToUri = require('image-to-uri');
//implementa
let imagem = imageToUri("caminho da sua imagem");
Here`s another simple way, use it when listing your images这是另一种简单的方法,在列出图像时使用它
@{
if (item.ImageData != null)
{
string imageBase64 = Convert.ToBase64String(item.ImageData);
string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);
<img src="@imageSrc" width="100" height="100" />
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.