簡體   English   中英

如何在sails.js 或通常在服務器端JavaScript 中將圖像轉換為base64 編碼的數據URL?

[英]How do I convert an image to a base64-encoded data URL in sails.js or generally in the servers side JavaScript?

我正在sails.js制作一個小應用程序,我需要將圖像存儲在數據庫中。 為此,我需要將圖像轉換為 base64 編碼的數據 URL,以便我可以將其保存為我的帆模型中的字符串。 但是,我不知道如何將其轉換為這種形式。 所有關於將圖像轉換為 base64 編碼的數據 URL 的較舊問題都被問到,他們回答了關於在客戶端執行此操作的問題。 但是,我想在服務器端執行此操作,同時我將通過發布請求獲取圖像。 我怎樣才能做到這一點?

據我了解,您想將文件轉換為 base64 編碼的字符串。 文件是否是圖像,這無關緊要。

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');
}

用法:

var base64str = base64_encode('kitten.jpg');

來源

它可以通過readFileSync實現,將圖像路徑作為第一個參數傳遞,將編碼選項作為第二個參數傳遞。 如下圖所示:

var fs = require('fs');

var imageAsBase64 = fs.readFileSync('./your-image.png', 'base64');

根據 節點文檔:

fs.readFileSync(path[, options])

fs.readFile() 的同步版本。 返回路徑的內容。

如果指定了編碼選項,則此函數返回一個字符串。 否則它返回一個緩沖區。

//可以使用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");

這是另一種簡單的方法,在列出圖像時使用它

@{
    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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM