Strange behavior when converting images to base64 using Jimp and Javascript - javascript

I have the code in Javascript that I paste below, the result obtained with method 1 is correct, that is, an image in base64 format when the conversion starts from reading a file.
But when I use the value returned by Jimp the conversion is done to "image/octet-stream" format, any suggestions?
var bitMap = new Jimp({ data: Buffer.from(gray.data), width: this.PicMatrixX, height: this.PicMatrixY, mime: Jimp.MIME_JPEG }, (err, image,) => {
image.write(this.PatNo + "_" + this.PatMeasNo + '.jpg')
})
this.base64 = fs.readFileSync(this.PatNo + "_" + this.PatMeasNo + '.jpg', "base64"); // Method 1
this.imagen = new Buffer.from(bitMap.bitmap.data).toString("base64") //Method 2

Related

Javascript - How would you make a record unique by adding a number?

Right now when file already exist I added prefix which is a timestamp to the filename to make it unique.
But instead of using timestamp I want to use ordinal suffix or add a number to the filename.
I would add an incremented number to the filename if the file exists. But can't quite wrap my head around how to do this in a good way.
Using timestamp works but its too long like when we display the filename it would be like for example so instead of using timestamp I just want to increment a number to a filename.
Hellworldfilename - 1593024232 - timestamp is too long , not a good idea.
It should based from existing records in the database . If for example I add a file with filename Hellworldfilename and it already existed then the new filename would be Hellworldfilename-1 , and if I add Hellworldfilename again the new filename would be Hellworldfilename-2 and so on and so forth. Any idea how we can make a filename everytime unique ?
Let me give an example. let us say I have 3 files in the database with filesname
DOC
DOC-1
DOC-2
If I add a file with filename DOC the new filename would be now DOC-3.
#Code for checking if file exists
const file = await context.service.Model.findOne({
where: { humanId: record.id, filename: data.filename },
paranoid: false,
});
if (file) {
const prefix = Date.now().toString();
// eslint-disable-next-line no-undef
const fileParts = data.filename.split('.');
filename = `${fileParts[0]}-${prefix}.${fileParts[1]}`;
You will need to check whether the filename ends with -somenumber. If so, then you can extract that number and increment it. Otherwise put 1 into the result:
function getNumberedFileName(fileN) {
//These are value initializations to cope with the situation when the file does not have a .
var fileName = fileN;
var fileExtension = "";
var lastDotIndex = fileN.lastIndexOf(".");
if ((lastDotIndex > 0) && (lastDotIndex < fileN.length - 1)) { //We are not interested in file extensions for files without an extension hidden in UNIX systems, like .gitignore and we are not interested in file extensions if the file ends with a dot
fileName = fileN.substring(0, lastDotIndex);
fileExtension = "." + fileN.substring(lastDotIndex + 1);
}
var lastDashIndex = fileName.lastIndexOf("-");
if ((lastDashIndex > 0) && (lastDashIndex < fileName.length - 1)) {
var lastPart = fileName.substring(lastDashIndex + 1);
if (!isNaN(lastPart)) {
var index = parseInt(lastPart) + 1;
return fileName.substring(0, lastDashIndex) + "-" + index + fileExtension;
}
}
return fileName + "-1" + fileExtension;
}
You could declare an object filenames in the global scope like
const filenames={};
and use it for keeping track of already opened files.
Below I defined a function makeUnique() hilighting the ideas I mentioned here before. It turns out I had to tweak my code a little bit but here is a working snippet:
const makeUnique=(function(){
const filenames={};
return function(fn){
const fileParts=fn.split(".");
const prefix=filenames[fn]!=null
? ++filenames[fn]
: filenames[fn]=0;
if (prefix) fileParts[Math.max(fileParts.length-2,0)]+='-'+prefix;
return fileParts.join('.')
}
})();
console.log(["abc","d.e.f.c","abc","ghi","abc","abc.txt","def",
"abc.txt","d.e.f.c","abc.txt","abc"].map(makeUnique))
.as-console-wrapper {max-height:100% !important}
I used an IIFE to generate a protected scope for the static object filenames. This is now accessible by all calls of makeUnique() but otherwise "private", i. e. cannot be modified accidentally from anywhere else.

How To Convert Values Into Sha-1 And Base64 In Javascript

I want to convert these values into Sha-1 and after that I want to convert again into base64. I tried lots of methods. But , none of them work.
var nonce = 5;
var unixtm = 6;
var pw = '123';
var shapw = nonce+ ' + ' +unixtm+ ' + ' +pw; //5 + 6 + 123
I mean , First of all I want to convert 'shapw' into Sha-1 and after that convert into Base64. Here is the formula -
FinalPw = Base64 ( SHA-1 ( nonce + created + SHA-1 ( password ) ) )
How can I do this ??
There are a lot of libraries which could help you to create SHA1 hash. Here for example https://github.com/emn178/js-sha1. Install it and use like
sha1('Message to hash');
var hash = sha1.create();
hash.update('Message to hash');
hash.hex();
For base64 there are btoa() (to base64) and atob() (from base64) functions.

How to assign default directory for every image stored in Amazon S3?

Every image chosen from the user will be stored in Amazon S3
this is my code
key: function ( file ) {
var user = Meteor.users.findOne( this.userId );
return user.emails[0].address + "/screenshots" + "/" + file.name;
}
Based on my code, the image will be stored in the user's email directory then the screenshots folder then the file name.
the problem is if the user wanted to store two images of the same name. The last picture will overwrite the first one.
i tried this solution
key: function ( file ) {
var today = new Date();
var user = Meteor.users.findOne( this.userId );
return user.emails[0].address + "/screenshots" + "/" + today + file.name;
}
it didn't work because the current date have spaces so i can't load the image later in the client because of the spaces.
Any idea of a way i can use to give every image a unique name? with no spaces?
You can generate a random hex string for each one:
key: function ( file ) {
var unique = Random.hexString(16);;
var user = Meteor.users.findOne( this.userId );
return user.emails[0].address + "/screenshots" + "/" + unique + file.name;
}
Random should be part of the default set of packages you get when you create a Meteor project.

How can I save image as base 64?

I am using phantom js to retrieve the image's strings and then I encode them with base 64.
var content = btoa(unescape(encodeURIComponent(imagestring)));
self.writeFile(pathToFolder + fileTitle, content);
But images are not displayed. It says they are damaged.
How can I save an image like that?
If you want save image as base64 with JavaScript, you can try with this code:
var fs = require('fs');
// string generated by canvas.toDataURL()
var img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0"
+ "NAAAAKElEQVQ4jWNgYGD4Twzu6FhFFGYYNXDUwGFpIAk2E4dHDRw1cDgaCAASFOffhEIO"
+ "3gAAAABJRU5ErkJggg==";
// strip off the data: url prefix to get just the base64-encoded bytes
var data = img.replace(/^data:image\/\w+;base64,/, "");
var buf = new Buffer(data, 'base64');
fs.writeFile('image.png', buf);

CSV exported from browser not displaying special character correctly on Excel

I am trying to export some data in csv format, it is fetched from my database (mongodb) with AJAX calls.
The problem is that special characters (e.g é à) are not displayed correctly in Excel after the CSV import.
However, they are correctly displayed on LibreOffice/Open Office, Google Spreadsheetm, and any text editor I could try.
I assume that the file is encoded in UTF-16 since it's generated from javascript.
Here's how I created the export in JavaScript (this is AngularJS) :
$scope.downloadCityCSV = function() {
$scope.csvURL = 'building';
var data = 'email;first name;last name;Email confirmé;city;quantity;date\n';
$scope.campaignData.cityVotes.forEach(function(vote) {
var customer = vote.customer;
data += customer.email +';' + customer.firstName +';' + customer.lastName +';' + (customer.accountConfirmed?"O":"N") +';' + vote.cityProposal + ';' + vote.quantity + ';' + vote.created + '\n';
});
var blob = new Blob([data], { type : 'text/csv' });
$scope.csvURL = (window.URL || window.webkitURL).createObjectURL(blob);
};
Did I do something wrong?

Categories