Bug when converting image buffer back to base64 - javascript

I am getting a strange bug where, when I convert a base64 string to an image buffer (Buffer.from(image, "base64")) and back to base64 (.toString("base64")) the resulting base64 string is missing its formatting (dataimage/pngbase64 instead of data:image/png;base64) as well as missing g== at the end. This results in the image being "corrupt" and not rendering when I put it in an <img /> in the frontend. The current workaround I'm using is the following:
image.toString("base64").replace("dataimage/pngbase64", "data:image/png;base64,") + "g=="
but this is far from an optimal solution and I would like to not use this sort of workaround.
This is where I bufferize the image (image is base64) and store it in the database
t.field("createModel", {
type: $name,
args: { input: nonNull(arg({ type: createModelInput.name })) },
resolve: async (_, args) => {
const { image, name, manufacturerId, identifiers } = args.input;
console.log(image) // correct base64 image from frontend
const buffedImage = Buffer.from(image, "base64");
console.log(buffedImage.toString("base64")) // not the same as image above: missing formatting & g== at the end
return await prisma.model.create({
data: {
image: buffedImage,
name,
identifiers,
manufacturer: {
connect: {
id: manufacturerId,
},
},
},
});
},
});
Please tell me any further information is needed.

The Base64 part of the string doesn't start until after the ,; the data: part is a scheme, the image/png part is a content type, and the base64, part is an indicator that what follows it is Base64 encoded text. So you're asking to convert non-Base64 data when you try to use that entire string as Base64.
You have to remove that prefix first, because it's not part of the Base64 data. It's just part of the data: URI.

Related

WordPress media library with metadata limit

I want to create a media library window. attachment should filter with mime types and metadata.
the mime-type filter is done. How can I build a metadata filter just for this?
function upload_image_tinymce(e) {
e.preventDefault();
var $input_field = $('.mce-my_input_image');
var custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Add Video',
button: {
text: 'Add Video'
},
library: {
type: [
'video/MP4',
'video/quicktime',
'video/x-m4v',
],
},
multiple: false
});
custom_uploader.on('select', function() {
var attachment = custom_uploader.state().get('selection').first().toJSON();
$input_field.val(attachment.id);
});
custom_uploader.open();
}
I cant help you with the whole filter code (not enoth knowlage ...)
But you can use the hook wp_get_attachment_metadata('attachment id') to get an array with the whole metadata of the attachment.
$meta = wp_get_attachment_metadata(126);
Will produce an array with the metadata from the attachment 126.
$cam = $meta[camera]
$cam will then hold the camera string from the metadata ...
Not much but maybe it will lead you a little bit in the right direction.

How to upload contentBytes chunk by chunk on Graph url return by createUploadSession graph API?

As per microsoft graph API documentation the createUploadSession graph API only return the URL where attachment can upload but how to upload attachment chunk by chunk in javascript? does anyone knows? Thanks in advance.
I'm referring this reference
Here is the reference for attaching the Attachment to a post in JavaScript, Please refer this Document
const options = {
authProvider,
};
const client = Client.init(options);
const reply = {
post: {
body: {
contentType: 'text',
content: 'Which quarter does that file cover? See my attachment.'
},
attachments: [{
'#odata.type': '#microsoft.graph.fileAttachment',
name: 'Another file as attachment',
contentBytes: 'VGhpcyBpcyBhIGZpbGUgdG8gYmUgYXR0YWNoZWQu'
} ]
}
};
await client.api('/groups/1848753d-185d-4c08-a4e4-6ee40521d115/threads/AAQkADJUdfolA==/reply')
.post(reply);
Hope this helpful.

How to get a file in pure binary

I have a file that I upload using antdUpload
The html renderer :
<Upload
beforeUpload={((file: RcFile, fileList: RcFile[]): boolean => {this.requestUpload(file, (fileList.length || 0 )); return false;})}
></Upload>
The code part :
requestUpload(file: RcFile, nbFile: number): void {
const r = new FileReader();
r.onload = (): void => {
FileHelper.uploadFile({
filename: file.name,
filepath: `${this.props.datastoreId}/${this.props.itemId}/${this.props.fieldId}/${file.name}`,
file: r.result,
field_id: this.props.fieldId,
item_id: this.props.itemId || '',
d_id: this.props.datastoreId || '',
p_id: this.props.projectId || '',
display_order: nbFile
}).subscribe()
};
r.readAsArrayBuffer (file);
}
So I get an RcFile (which just extend the type file) from that moment, I don't know what to do to get a raw binary of the file. my API only work with a raw binary, and nothing else. so I need that file: r.result, to be a pure binary raw data.
I found other stackoverflow question, but they all say how it should be (using base64 or other) but not how to do it if you have no other option to change it.
How can I achieve this ?
According to the file-upload tool you linked (ng-file-upload) you should first: "Ask questions on StackOverflow under the 'ng-file-upload' tag." So, add that tag to this post.
Then if I Ctrl+F for "binary" on the docs, I see this:
Upload.http({
url: '/server/upload/url',
headers : {
'Content-Type': file.type
},
data: file
})
Looks like they're passing a file object as the data, and the w/e the file type is in the header. I haven't tried this though...

Parsing JSON-like file type to JSON in JavaScript

I have lots of files with an unusual file extension.
I need to read the files using JavaScript and convert their contents to JSON or regular JavaScript objects.
Is this even possible?
I have some hope, because the files are already structured very similar to JSON:
// file.unusualFileType
Page: {
id: P001
Title: "Page Title"
URL: "/home"
Elements: {
Button: {
Text: "Click me"
Action: SAVE
}
}
}
EDIT: HÃ¥ken Lid kindly provided a solution for my particular use case. Out of curiosity I would still be interested in how to read any file as a string with JavaScript and how one could possible parse such a string.
It would be valid yaml if you strip out the curly brackets. You can use js-yaml to parse the sample data, so maybe it works with the rest of your files too?
const rawData = `
Page: {
id: P001
Title: "Page Title"
URL: "/home"
Elements: {
Button: {
Text: "Click me"
Action: SAVE
}
}
}`
const yamlData = rawData.replace(/[{}]/g, '')
console.log(jsyaml.load(yamlData))
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-yaml/3.13.1/js-yaml.min.js"></script>

Write EXIF data to image stream Node.js

I found a nice npm package that allows you to read and write Exif data to images, https://github.com/Sobesednik/node-exiftool.
The challenge that I have is that it requires you to provide the path to an image. So, the image has to be written to disk if you want to modify the EXIF using this package. Is there an easy way to check/read the EXIF, and if necessary, write EXIF data to an image stream?
var imageURL = 'https://nodejs.org/static/images/logos/nodejs-new-pantone-black.png'
var upstreamServer = 'http://someupstreamserver/uploads'
request
.get(imageURL)
.pipe(
// TODO read EXIF
// TODO write missing EXIF
request
.post(upstreamServer, function(err, httpResponse, body){
res.send(201)
})
)
EDIT: This question was also asked on node-exiftool
i had a similar task. I had to write physical dimensions and additional metadata to PNG files. I have found some solutions and combined it into one small library.
png-metadata
it could read PNG metadata from NodeJS Buffers, and create a new Buffers with new metadata.
Here is an example:
const buffer = fs.readFileSync('1000ppcm.png')
console.log(readMetadata(buffer));
withMetadata(buffer,{
clear: true, //remove old metadata
pHYs: { //300 dpi
x: 30000,
y: 30000,
units: RESOLUTION_UNITS.INCHES
},
tEXt: {
Title: "Short (one line) title or caption for image",
Author: "Name of image's creator",
Description: "Description of image (possibly long)",
Copyright: "Copyright notice",
Software: "Software used to create the image",
Disclaimer: "Legal disclaimer",
Warning: "Warning of nature of content",
Source: "Device used to create the image",
Comment: "Miscellaneous comment"
}
});
It could be modified to be used with streams, for example, you could implement WritableBufferStream class.
const { Writable } = require('stream');
/**
* Simple writable buffer stream
* #docs: https://nodejs.org/api/stream.html#stream_writable_streams
*/
class WritableBufferStream extends Writable {
constructor(options) {
super(options);
this._chunks = [];
}
_write(chunk, enc, callback) {
this._chunks.push(chunk);
return callback(null);
}
_destroy(err, callback) {
this._chunks = null;
return callback(null);
}
toBuffer() {
return Buffer.concat(this._chunks);
}
}

Categories

Resources