how to save domtoimage to localstorage - javascript

i use dom-to-image javascript package for making div element to png file, i want to save this png file to locastorage and displayed the image on next page how to make it?
i tried localStorage.setItem('testCart', blob) , and the result value is [HTML object blob], i know this is wrong, what should i do?
here is mycode
function onSaveDpn() {
domtoimage.toBlob(document.getElementById("custom-cloth"))
.then(function (blob) {
// code to download file as .png
window.saveAs(blob, "sakaw-custom-depan.png");
// code to save into localstorage
localStorage.setItem( what should I write? )
});
}

Edit, I solved my problem with this
https://www.geeksforgeeks.org/how-to-convert-blob-to-base64-encoding-using-javascript/
this is my new code
function onSaveDpn() {
domtoimage
.toBlob(document.getElementById("custom-cloth"))
.then(function (blob) {
// window.saveAs(blob, "sakaw-custom-depan.png");
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
var base64String = reader.result;
localStorage.setItem("scart", base64String);
};
});
}
I hope this can help you guys

Related

Adding a watermark to a image before uploading with watermarkjs

I'm trying to add a watermark to a image with watermark.js before it get uploaded but, I can't quite figure out how to do it.
With the code i got underneath the upload part of the uploadFile function is working but, the image data gets lost within the watermark script somehow and the uploaded image on AWS S3 is just a small transparent square.
I've also added my function to preview the image, and this is working fine and displays the image with the watermark as it is supposed to.
So why is one of the functions working while the other have problems, what am I doing wrong in the uploadFile function?
const uploadFile = file => {
axios.get(`/api/imageUpload/${file.type}`)
.then(uploadConfig => {
watermark([file, '../static/images/watermark_white.png'])
.image(watermark.image.lowerRight())
.then(img => {
axios.put(uploadConfig.data.url, img, {
headers: {
"Content-Type": file.type
},
}).then(() => {
props.onUpload(uploadConfig.data.key);
});
});
});
};
const previewFile = file => {
if (!isImage(file)) {
return;
}
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = () => {
let img = document.createElement("img");
img.src = reader.result;
watermark([img, '../static/images/watermark_white.png'])
.image(watermark.image.lowerRight())
.then(function (img) {
document.getElementById("gallery").appendChild(img);
});
};
};
Turns out I only had to change .image(watermark.image.lowerRight()) to .blob(watermark.image.lowerRight()) and everything works.

Feed FileReader from server side files

I´m starting to customize/improve an old audio editor project. I can import audio tracks to my canvas VIA drag&drop from my computer. The thing is that I also would like to use audio tracks already stored in the server just clicking over a list of available tracks... instead of use the <input type="file"> tags. How can I read the server side files with a FileReader?Ajax perhaps? Thanks in advance.
This is the code for the file reader:
Player.prototype.loadFile = function(file, el) {
//console.log(file);
var reader = new FileReader,
fileTypes = ['audio/mpeg', 'audio/mp3', 'audio/wave', 'audio/wav'],
that = this;
if (fileTypes.indexOf(file.type) < 0) {
throw('Unsupported file format!');
}
reader.onloadend = function(e) {
if (e.target.readyState == FileReader.DONE) { // DONE == 2
$('.progress').children().width('100%');
var onsuccess = function(audioBuffer) {
$(el).trigger('Audiee:fileLoaded', [audioBuffer, file]);
},
onerror = function() {
// on error - show alert modal
var tpl = (_.template(AlertT))({
message: 'Error while loading the file ' + file.name + '.'
}),
$tpl = $(tpl);
$tpl.on('hide', function() { $tpl.remove() })
.modal(); // show the modal window
// hide the new track modal
$('#newTrackModal').modal('hide');
};
that.context.decodeAudioData(e.target.result, onsuccess, onerror);
}
};
// NOTE: Maybe move to different module...
reader.onprogress = function(e) {
if (e.lengthComputable) {
$progress = $('.progress', '#newTrackModal');
if ($progress.hasClass('hide'))
$progress.fadeIn('fast');
// show loading progress
var loaded = Math.floor(e.loaded / e.total * 100);
$progress.children().width(loaded + '%');
}
};
reader.readAsArrayBuffer(file);
};
return Player;
Thanks for the suggestion micronn, I managed to make a bypass without touch the original code. The code as follows is the following:
jQuery('.file_in_server').click(function()
{
var url=jQuery(this).attr('src');//Get the server path with the mp3/wav file
var filename = url.replace(/^.*[\\\/]/, '');
var path="http://localhost/test/audio/tracks/"+filename;
var file = new File([""], filename); //I need this hack because the original function recives a buffer as well as the file sent from the web form, so I need it to send at least the filename
var get_track = new XMLHttpRequest();
get_track.open('GET',path,true);
get_track.responseType="arraybuffer";
get_track.onload = function(e)
{
if (this.status == 200) //When OK
{
Audiee.Player.context.decodeAudioData(this.response,function(buffer){ //Process the audio toward a buffer
jQuery('#menu-view ul.nav').trigger('Audiee:fileLoaded', [buffer, file]); //Send the buffer & file hack to the loading function
},function(){
alert("Error opening file");
jQuery('#newTrackModal').modal('hide');
});
}
};
get_track.send();
});
After this, in the fileLoaded function, the track is added to the editor.
var name = 'Pista ' + Audiee.Collections.Tracks.getIndexCount();
track = new TrackM({buffer: audioBuffer, file: file, name: name}); //being audioBuffer my buffer, file the fake file and name the fake file name
Audiee.Collections.Tracks.add(track);
And... thats it!

How to process an image in url to upload on the server in cordova

I am having a problem with this code. i wanna process the cordova android image url ( ie. stored in localStorage ) to upload in my web server.
function processImages(list, i){
var images = list[i].images;
images && images.forEach(function(image, j){
window.resolveLocalFileSystemURI(image, function(entry) {
var reader = new FileReader();
reader.onloadend = function(evt) {
list[i].images[j] = evt.target.result;
}
reader.onerror = function(evt) {
alert("error");
}
entry.file(function(f) {
//alert("Image is added");
reader.readAsDataURL(f);
}, function(e) {
alert('Image process error : '+e);
});
});
});
}
This code runs good if i am enabling #alert("Image is added"); this alert.
without this alert the app is shutting down by giving error unfortunately appname has stopped.
Its also not working for n number of images of size more than 2mb.
Note : consider async call and image size is more than 2mb each minimum 10 image per record.
Please help me !!!
Thanks

pass input file to background script

I want to pass the input file from content page to extension background script, and then load it with FileReader() in the extension background script.
So in the web page I have a <input type="file"> and from onchange event I pass the file from content script to background page like this:
var myfile = document.getElementById('fileid').files[0];
chrome.runtime.sendMessage({myevent: "start", inputfile: myfile}, function(response) {});
in the background script I have this:
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
if(message.myevent==="start")
{
var reader = new FileReader();
reader.onload = function(e) {
// file is loaded
}
reader.readAsArrayBuffer(message.inputfile);
}
});
but FileReader not load it, I'm not sure if this is correct way , but all i need is to pass the input file element to background script and load it with FileReader to send it with HTTP POST from background script. Please tell me what is wrong or how to do it correctly. It will help a lot if I see a sample code, because I'm new to chrome extension development, and not so experienced.
All messages send through the Chrome extension messaging API MUST be JSON-serializable.
If you want to get the contents of a file at the background page, you'd better create a (temporary) URL for the File object, pass this URL to the background page and use XMLHttpRequest to grab its contents:
// Create URL
var url = URL.createObjectURL(myfile);
// Pass URL to background page (ommited for brevity) and load it..
var x = new XMLHttpRequest();
x.onload = function() {
var result = x.response;
// TODO: Use [object ArrayBuffer]
};
x.open('GET', url); // <-- blob:-url created in content script
x.responseType = 'arraybuffer';
x.send();
Though why do you want to send the file to the background page? Content scripts can also send cross-origin requests.
This works for chrome. You could find the whole production code here.
https://github.com/Leslie-Wong-H/BoostPic/tree/7513b3b8d67fc6f57718dc8b9ff1d5646ad03c75/BoostPic_Chrome/js
main.js:
// Crossbrowser support for URL
const URLObj = window.URL || webkitURL;
// Creates a DOMString containing a URL representing the object given in the parameter
// namely the original Blob
const blobUrl = URLObj.createObjectURL(imageBlob);
console.log(blobUrl);
chrome.runtime.sendMessage(blobUrl, (res) => {
imgUrl = res;
console.log(imgUrl);
clearInterval(refreshIntervalId);
// To prevent that it happens to halt at " Image uploading ..."
setTimeout(() => {
var imgUrlText = document.querySelector(imgUrlTextBoxId);
imgUrlText.value = imgUrl;
}, 1000);
// double check to clear interval to prevent infinite error loop of LoadingStateOne
// Hope it works.
setTimeout(() => {
clearInterval(refreshIntervalId);
}, 500);
console.log("Stop uploading state message");
background.js:
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.startsWith("blob")) {
console.log("RECEIVED");
getBase64Url(request).then((res) => {
console.log("Arrived here");
// Acquired from https://stackoverflow.com/questions/18650168/convert-blob-to-base64/18650249#
const reader = new FileReader();
reader.readAsDataURL(res);
reader.onloadend = function () {
const base64data = reader.result;
console.log(base64data);

Deleting a file in FileSystem API after read is finished?

So I'm stuck trying to figure this out.
fileEntry.file(function(file){
var reader = new FileReader();
reader.onloadend = function (e) {
var anchor = document.createElement("a");
anchor.setAttribute('href', "data:text/tsv;charset=UTF-8," + encodeURIComponent(this.result));
anchor.setAttribute("download", "log.tsv");
anchor.innerHTML = "Download Log Now";
document.body.appendChild(anchor);
alert("Download by clicking the damn link at the bottom.");
//delete the file?
}
reader.readAsText(file);
});
So my question is how do you delete the file after it's been read? I've tried doing fileEntry.remove(function(){console.log("File Removed.")}); where the comment is but that doesn't work.
Any ideas?
You can have a look on promise-based bro-fs where this is more clean:
fs.init()
.then(() => fs.readFile('file.txt'))
.then(content => console.log(content))
.then(() => fs.unlink('file.txt'))

Categories