NodeJS base64 图像编码/解码不太工作

2024-02-01

我一直在尝试将发布到nodeJS(和express框架)的图像保存到数据库,但遇到了一些麻烦。忽略所有的 Web 处理,我认为我已经将问题范围缩小到了 Node.js 中进行 Base64 编码的方式。我相信下面过于简化的示例应该可以工作,但输出图像总是损坏。

示例 (1) 加载图像 (2) 保存 if (image_orig)以确认节点可以正确读取文件。这总是有效的。 (3) 我获取图像并对其内容进行 Base64 编码,(4) 然后对其进行解码。最终输出图像(image_decoded) 总是被损坏。

帮助! (OSX Lion 上的 Node.js 0.6.0)

console.log("starting");
process.chdir(__dirname);

var fs = require("fs");

var image_origial = "image.jpg";
fs.readFile(image_origial, function(err, original_data){
    fs.writeFile('image_orig.jpg', original_data, function(err) {});
    var base64Image = new Buffer(original_data, 'binary').toString('base64');
    var decodedImage = new Buffer(base64Image, 'base64').toString('binary');
    fs.writeFile('image_decoded.jpg', decodedImage, function(err) {});
});

我认为您有点误解了编码参数的用法。如果您要指定编码“二进制”,那么您需要一致地执行此操作。但实际上你根本不需要它。您似乎混淆了 Buffer 与二进制字符串的使用。

// This tells node to load the file into a Buffer 'original_data' because you
// have not specified an encoding for the returned values. If you provided an
// encoding, then original_data would be a string with that encoding.
fs.readFile(image_origial, function(err, original_data){

    // This tells node to take that buffer, and write it to the new filename.
    // Again no encoding is provided, so it will assume a Buffer or utf8 string.
    fs.writeFile('image_orig.jpg', original_data, function(err) {});

    // This tells node to create a new buffer from the old buffer, which means
    // it will iterate over original_data copying the bytes one at a time. But
    // they will be identical buffers. It will ignore the 'binary' argument
    // since the object you are passing isn't a string.
    // Then it encodes the content of that Buffer to base64, which is fine.
    var base64Image = new Buffer(original_data, 'binary').toString('base64');

    // Here you decode the base64 to a buffer, which is fine, but then you
    // convert the buffer into a string with encoding 'binary'. This means that
    // it is a string object whose code points are bytes of the buffer.
    var decodedImage = new Buffer(base64Image, 'base64').toString('binary');

    // Here you try to write that String object to a file. Since the argument you
    // have given is a string and you have not given an encoding argument for the
    // write command, then it will assume that 'utf8' is the encoding. It will try to
    // decode your binary string into a utf8 encoded buffer, and write that buffer.
    // This will cause it to fail because that encoding conversion is wrong.
    // Really through, 'binary' is just wrong to use. Buffers are already binary.
    fs.writeFile('image_decoded.jpg', decodedImage, function(err) {});
});

下一个示例可以工作,但效率非常低,因为不需要一直更改编码,但我只是想清楚地表明它。如果您确实想要使用特定的编码,则需要确保一致。这些函数中的每一个都有一个编码参数。

fs.readFile(image_origial, 'binary', function(err, original_data){
    fs.writeFile('image_orig.jpg', original_data, 'binary', function(err) {});
    var base64Image = new Buffer(original_data, 'binary').toString('base64');
    var decodedImage = new Buffer(base64Image, 'base64').toString('binary');
    fs.writeFile('image_decoded.jpg', decodedImage, 'binary', function(err) {});
});

这是正确的做法。将所有内容保留为缓冲区,除非您将其设为 base64。

fs.readFile(image_origial, function(err, original_data){
    fs.writeFile('image_orig.jpg', original_data, function(err) {});
    var base64Image = original_data.toString('base64');
    var decodedImage = new Buffer(base64Image, 'base64');
    fs.writeFile('image_decoded.jpg', decodedImage, function(err) {});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

NodeJS base64 图像编码/解码不太工作 的相关文章

  • 下载 csv 文件 node.js

    我正在使用 node js 构建一个应用程序并尝试将数据下载为 csv 文件 我正在使用 json2csv https www npmjs com package json2csv https www npmjs com package j
  • 纤维/未来实际上有什么作用?

    下面这行代码的作用是什么 Npm require fibers future 我在网上查找示例 发现了一些这样的示例 Future Npm require fibers future var accessToken new Future 什
  • API 使用令牌向 odoo 进行身份验证

    我想使用令牌从 Express 应用程序向 Odoo 进行身份验证 我在用odoo xmlrpc https www npmjs com package odoo xmlrpc连接 Odoo 的节点模块 我的快递应用程序 Odoo 要求 A
  • 在文件之间共享 mqtt 客户端对象

    我这样连接到 MQTT mqtt js const mqtt require mqtt var options needed options var client mqtt connect mqtt someURL options clie
  • Jwt 签名和前端登录身份验证

    我有这个特殊的 jwt sign 函数 Backend const token jwt sign id user id process env TOKEN SECRET expiresIn 1m res header auth token
  • 护照本地猫鼬帐户注册的附加字段?

    我将 Passport local mongoose 与 Node js Express js MongoDB 一起用于 Web 应用程序 我想使用用户名字段 密码字段 公司名称字段和电话号码字段 所有字段 来注册用户作为字符串 但是 我只
  • 使用 React.js + Express.js 发送电子邮件

    我在 ES6 中使用 React js 构建了一个 Web 应用程序 我目前想要创建一个基本的 联系我们 页面并想要发送电子邮件 我是 React 新手 刚刚发现我实际上无法使用 React 本身发送电子邮件 我正在遵循教程nodemail
  • 如何在Electron WebView中连接到代理?

    因为我可以通过连接到免费代理服务器 或付费 目前用作电子 JS 解决方案作为桌面应用程序 代理列表服务器示例 http proxylist hidemyass com http proxylist hidemyass com 您可以使用 s
  • libxmljs 的替代品 [关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 目标 使用 Node js 访问网页 使用 xpath 语法操作 DOM 并打印新的 DOM libxm
  • NestJS e2e 测试模拟会话装饰器

    我正在尝试使用 supertest 编写一个 e2e 测试 其中我的控制器实际上使用了 Session 装饰师 然而 我不想承担使用数据库连接等启动会话的全部负担 因此测试中的我的应用程序实际上并未初始化会话 相反 我想首先模拟掉装饰器提供
  • 根据特定字符获取整个字符串或子字符串

    我有一个包含 MIME 类型的字符串 例如application json 现在我想将其与实际的 HTTP 标头进行比较 在本例中content type 如果标头包含 MIME 类型 那么就很简单 if mimeType contentT
  • Node.js 和 Passport 对象没有 validPassword 方法

    我正在使用 Node js Express Passport 创建一个简单的身份验证 本地 到目前为止我所达到的效果是 当输入错误的用户名或密码时 用户将被重定向到错误页面 但是当用户输入正确的用户名和密码时 我收到此错误 node mod
  • 在 Node.js 中,setTimeout() 会阻止事件循环吗?

    如果我有一个简单的 setTimeout 函数 并将其设置为 10 秒 整个服务器在那10秒内就死机了 这是真的 这就是我听到的 答案是no 你的链接是什么Node js 如何重新创建 setTimeout 函数而不阻塞事件循环 https
  • 在回调中使用await(Microsoft Bot Framework v4 Nodejs)

    我正在尝试将回复发送回chatbot emulator从内部回调 async getUserDetails step console log inside get userdetaiuls modeiule this userDBObjec
  • 我在 MacBook M1 max 中的 nodejs 连接到数据库 oracle 时遇到问题帮助我

    Node js 中的错误消息 nodemon 启动node server js错误 错误 DPI 1047 无法找到 64 位 Oracle 客户端库 dlopen Users pitidev ldb Downloads instantcl
  • 在heroku上部署时出错,/bin/sh: 1: webpack: not found

    这是我在 heroku 网站上手动部署时遇到的错误 首先 我在 json 文件中遇到错误 因此我指定了正在运行的 npm yarn 和 node 版本 这些错误似乎已经清除 现在我就是这样的人 并且已经搜索了谷歌 但似乎找不到太多关于修复它
  • 如何配置 Google 计算引擎以对 Nodejs 服务器使用 HTTPS?

    我想使用 https SSL 在 google 计算引擎中运行 nodejs 和 socket io 服务器 我安装了自签名证书https cloud google com compute docs load balancing http
  • 使用 Sequelize 实现单表继承

    有没有办法使用sequelize来创建单表继承 我希望有一个用于购买和 PartialPurchase 模型的 STI 其中我将有一个类型字段 该字段为 Purchase 或 PartialPurchase 以及类 Purchasing 和
  • 流星内存不足

    我正在使用流星来制作报废引擎 我必须执行一个 HTTP GET 请求 这会向我发送一个 xml 但这个 xml 大于 400 ko 我得到一个异常 内存不足 result Meteor http get http SomeUrl com 致
  • 查询为空 Node Js Sequelize

    我正在尝试更新 Node js 应用程序中的数据 我和邮递员测试过 我的开发步骤是 从数据库 MySQL 获取ID为10的数据进行更新 gt gt 未处理的拒绝SequelizeDatabaseError 查询为空 我认识到 我使用了错误的

随机推荐