Discord.js sending base64 encoded image to channel - node.js

i've been at this for days now and im stuck on this final part.
as the title suggests my creation receives a base64 encoded image. it then loads it into a buffer and attempts to send it to to a channel like so:
sfbuffer = new Buffer.from(base64_img, "base64");
const finalattach = new Discord.MessageAttachment(sfbuffer);
message.channel.send(finalattach);
it does send the buffer however it always results in this
example of base64 data that gets loaded
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAIAAADTED8xAAEA and so on...
i've tried sending it with file options (didn't even send), and as an embed using both .setimage and .attachfiles and both produce the same results. please im banging my head over this. all the google links are purple and i don't know what else to do D:

image buffers should NOT contain the
data:image/png;base64, part. only the non-human readable data
split the base64 string at the comma, load it into a attachment as a buffer and send attachment e.g.
const sfbuff = new Buffer.from(base64_img.split(",")[1], "base64");
const sfattach = new Discord.MessageAttachment(sfbuff, "output.png");
message.channel.send(sfattach)
Even though i figured it out, i couldn't of done it without Aviv lo
Thank you all :)

Try something like this:
replyMessage.Attachments.Add(new Attachment()
{
ContentUrl = $"data:image/jpeg;base64,{Convert.ToBase64String(bdata)}"
});
This post is answering similar questions.

Related

How to parse video stream coming from the nodejs server

I'm creating a video streaming service, the backend code look like this:
const stream = new Readable();
stream.push(movie.data.slice(start, end + 1));
stream.push(null);
stream.pipe(res);
This when run in postman, postman automatically parses it and give me a video in the response. But when I'm using it in my code, it gives me responses in random characters
`ftypmp42isommp42îmoovlmvhdè'#trak\tkhd&è#hmdia mdhd2òUÄGhdlrvideISO Media file produced by Google Inc.°minf$dinfdrefurl pstblstsdavc1hHHÿÿ2avcCBÀÿágBÀÚ¿åÀZ  AâÅÔhÎ<sttsù4stsc
dstco
õÆSLÕÆH?ÛÔHAÍ°G.4¥¹®4³¤(ù¯- Å
GÐ
î¿østszùHÕ7ÈÕI~hS<
©ÅºÒ 3k 7 (;²w¶¸¯Ð«¥y¾mÙEòÙÕÊ®ß
nºK|'eiõE^H2_&Z£ÇVpÛË?O*z"±ÿ{¢×Õg&°]Øe¡OË¿£½í¯¥^y§t=ª$®Ü'² ²-míÜÆ£%(¶zÎ,4qj z º5ªÓ#ã§
!ßó¢uÌÎÏ£¢¿ß(u;xû/]ù%¡ErµÒà1§5&¬¤'£,i5Ó3óØ(â[¬³föçÑÀH
[`
Now the problem is that I don't know what is this, how to parse it, how to display it as a video... Need help

NodeJS and Iconv - "ISO-8859-1" to "UTF-8"

I created a NodeJS application which should get some data from an external API-Server. That server provides its data only as 'Content-Type: text/plain;charset=ISO-8859-1'. I have got that information through the Header-Data of the server.
Now the problem for me is that special characters like 'ä', 'ö' or 'ü' are shown as �.
I tried to convert them with Iconv to UTF-8, but then I got these things '�'...
My question is, what am I doing wrong?
For testing I use Postman. These are the steps I do to test everything:
Use Postman to trigger my NodeJS application
The App requests data from the API-Server
API-Server sends Data to NodeJS App
My App prints out the raw response-data of the API, which already has those strange characters �
The App then tries to convert them with Iconv to UTF-8, where it shows me now this '�' characters
Another strange thing:
When I connect Postman directly to the API-Server, the special characters get shown as they have too without problems. Therefore i guess my application causes the problem but I cannot see where or why...
// Javascript Code:
try {
const response = await axios.get(
URL
{
params: params,
headers: headers
}
);
var iconv = new Iconv('ISO-8859-1', 'UTF-8');
var converted = await iconv.convert(response.data);
return converted.toString('UTF-8');
} catch (error) {
throw new Error(error);
}
So after some deeper research I came up with the solution to my problem.
The cause of all trouble seems to lie within the post-process of axios or something similar. It is the step close after data is received and convertet to text and shortly before the response is generated for my nodejs-application.
What I did was to define the "responseType" of the GET-method of axios as an "ArrayBuffer". Therefore an adjustment in axios was necessary like so:
var resArBuffer = await axios.get(
URL,
{
responseType: 'arraybuffer',
params: params,
headers: headers
}
);
Since JavaScript is awesome, the ArrayBuffer provides a toString() method itself to convert the data from ArrayBuffer to String by own definitions:
var response = resArBuffer.data.toString("latin1");
Another thing worth mentioning is the fact that I used "latin1" instead of "ISO-8859-1". Don't ask me why, some sources even recommended to use "cp1252" instead, but "latin1" workend for me here.
Unfortunately that was not enough yet since I needed the text in UTF-8 format. Using "toString('utf-8')" itself was the wrong way too since it would still print the "�"-Symbols. The workaround was simple. I used "Buffer.from(...)" to convert the "latin1" defined text into a "utf-8" text:
var text = Buffer.from(response, 'utf-8').toString();
Now I get the desired UTF-8 converted text I needed. I hope this thread helps anyone else outhere since thse informations hwere spread in many different threads for me.

Node Server and base64

I am having some issues converting a payload received (req.body) to a correctly formatted base64 string.
The payload is received and looks like the below example. I know that it's encrypted coming in but I'm wondering if there is anything that could be happening node server side that makes it look like this, it seems malformed and not how it should be
body: '&R۽5�l|L�\u001b�\u0014햱����\u00020#��[cV[AD&P�\u0001��˯���\n' +
`#B軉�6Y¤�\u0010�l�\u0012"D�dʦ�nb�g���\u0017����߉�{�a\u000e�:��\u0014\u0005�4\u0018!��u\u001e��s!վ]�\u0011KɆ�<!\u001d��#a�Ӿǥ+\f�iWEź�����:^�Վߎ�NP�M�G�_x�}�b1W�t�\u000f?*�2N�s��\u0000\u0015\u001e��o��� |y.\u0004n�e��64z�eu3\u0007(��j�R�\u0001 jzO\u0012�IF\u0002��w_����%�\u001b\u0010��\u0010��5�\u0016�.1�\u0006�\f\u0014�$�|\u000e�E�5�����o�MΆA\u001a��\u0010���׽���-ܹ��\u0003�jV�0b\u0002�\u001f��\\^"\\���\u0000��%�̓B�TfI��3��2U���[#�ۍ�'bT�]�\u0007�������\u0016 �P��x?\u0014�ly*8\u00134�NR����<��\u0012^�"#�V���!\u0010=�\u0006�"r�c�a�/L���vq�<\u0015�\u0006H��\u0014�\u001f�m�~�Ֆ�\u0011>L+����Yw���٘�\u0007ur�&�i�B4\n` +
If I convert the payload to a base64 string then i get something like this (the + and / characters do not seem right)
var encryptedBytes = Buffer.from(req.body);
var encryptedStr = encryptedBytes.toString('base64');
console.log({encryptedStr});
{ encryptedStr: 'JlLbvTXvv71sfEzvv70b77+9fxTtlrHvv73vv73vv73vv70CMCPvv73vv71bY1ZbQUQmUO+/vQHvv73vv73Lr++/ve+/ve+/vQojQui7ie+/vTZZwqTvv70Q77+9bO+/vRIiRO+/vWTKpu+/vW5i77+9Z++/ve+/ve+/vRfvv73vv73vv73vv73fie+/vXvvv71hDu+/vTrvv73vv70UBe+/vTQYIe+/ve+/vXUe77+977+9cyHVvl3vv70RS8mG77+'}
If I compare this to a base64 string I grab from the request on an iOS device for example, these seem rather different, plus this base64 string below can be decrypted successfully, which implies the issue could be within node?
{ base64data: 'ZGRIUUJhR0dMc3BTVFdQSHppS3BZUDY1UmJWSkFmbnRpekg1a29nUnlFMGtZemExU0RwS1h0VHlNd1lHMnhRcEZiMjEzNEwwYXduNllHR1p0aU1HM3YzcWlyTnlSd2RWSmNHQldMRVVMWklWaGRpNzBNWHVPNkZaSnJBUWZ6YnBJbERESzBiTEpoUGVCS3ZiU1d2NnRIcktIb'}
So my question here, is there something i need to do node server side to correctly parse or translate the req.body ready to be converted into a base64 string?

Discord Embed Image Response

I am having trouble with a random response command I have for a Discord bot.
At the moment the command sends back everything as intended except for an image link.
I have a number of random responses in an array, mostly text responses and one image response.
When the embed reply does the image response just appears as the image link, can anyone help so when it responds the image appears?
Here is the code from the array and then the main file:
const jokeResponses = [
"joke1",
"joke2",
"joke3",
"https://i.imgur.com/HXLENiv.png"
]
module.exports = {jokeResponses}
const { jokeResponses } = require('./jokeResponses.js');
case "joke":
var response = jokeResponses [Math.floor(Math.random()*jokeResponses .length)];
embed.setColor('#f299cd')
embed.setTitle(message.author.username + '`s joke')
embed.setDescription(response);
message.channel.send(embed);
break;
I don't understand why when the image link comes back it just appears as the link and not the actual image.
Appreciate any help.
.setDescription() is for text only, you would have to use .setImage() to display a gif
.setImage(response)

Converting binary strings to Buffers in Node.js

I have a web service that takes a base 64 encoded string representing an image, creates a thumbnail of that image using the imagemagick library, then stores both of them in mongodb. I am doing this with the following code (approximately):
var buf = new Buffer(req.body.data, "base64"); //original image
im.resize({ srcData: buf, width: 256 }, function(err, stdout, stderr) {
this.thumbnail = new Buffer(stdout, "binary");
//store buf and stdout in mongo
});
You will notice that I am creating a Buffer object using the "binary" encoding, which the docs say not to do:
'binary' - A way of encoding raw binary data into strings by using
only the first 8 bits of each character. This encoding method is
deprecated and should be avoided in favor of Buffer objects where
possible. This encoding will be removed in future versions of Node.
First off I'm not sure what they are saying there. I'm trying to create a Buffer object and they seem to imply I should already have one.
Secondly, the source of the problem appears to be that the imagemagick resize method returns a string containing binary data. Doing typedef(stdout) return "string" and printing it out to the screen certainly appears to show a bunch of non-character data.
So what do I do here? I can't change how imagemagick works. Is there another way of doing what I'm trying to do?
Thats how I am doing the same with success, storing images in mongodb.
//original ---> base64
var thumbnail = new Buffer(req.body.data).toString('base64');
//you can store this string value in a mongoose model property, and save to mongodb
//base64 ---> image
var buffer = new Buffer(thumbnail, "base64");
I am not sure if storing images as base64 is the best way to do it
Please try this as your base64 might not be pre-handled:
var imgRawData =
req.body.images[0].replace(/^data:image\/png;base64,|^data:image\/jpeg;base64,|^data:image\/jpg;base64,|^data:image\/bmp;base64,/, "");
var yourBuffer = new Buffer(imgRawData, "base64");
Then, save the yourBuffer into MongoDB buffer.

Resources