Javascript [AngularJS] function to save canvas as image with custom name - javascript

I'm looking for a function which can save canvas as an image with custom name when save button is clicked. For now I have the following lines in my javascript function which take the canvas element and specify the format of the data:
var canvas1 = document.getElementById("canvasSignature");
var myImage = canvas1.toDataURL("image/png");
I don't know how to give a custom name of the image and how to make it download.
Any help will be appreciated.
Thanks

This is how I did it on a resent project
var dataURIToBlob = function(dataURI, callback) {
var binStr = atob(dataURI.split(',')[1]),
len = binStr.length,
arr = new Uint8Array(len);
for (var i = 0; i < len; i++) {
arr[i] = binStr.charCodeAt(i);
}
callback(new Blob([arr], {
type: 'image/png'
}));
};
var fileName = 'filename.png';
var base64 = canvas.toDataURL('png');
dataURIToBlob(base64, function(blob){
args.download = fileName;
args.href = URL.createObjectURL(blob);
});
};

html2canvas($("#container"), {
onrendered: function (canvas) {
var a = document.createElement("a");
a.download = "Dashboard.png";
a.href = canvas.toDataURL("image/png");
a.click();
}
});
put this code and you are done.

Related

Not able to view or download file on iPhone + SAPUI5

This code works great on tablets and desktop, but when I try on iPhone it is not downloading any file. Please help
if (aData.ExternalUrl === "") {
this.oModel.read("/GetAttachmentBase64Set('" + aData.DocumentId + "')", {
success: function (oData, oResponse) {
oList.setBusy(false);
var dataURI = oData.EvAttachmentData;
if (Device.system.tablet ||Device.system.phone) {
window.open(dataURI, "_blank");
return;
}
dataURI = dataURI.substring(dataURI.indexOf(",") + 1);
var raw = window.atob(dataURI);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for (var i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
var saveByteArray = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, name) {
var blob = new Blob(data, {
type: "octet/stream"
}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = name;
a.click();
window.URL.revokeObjectURL(url);
};
}());
saveByteArray([array], aData.Filename);
oList.removeSelections();
},
This code works great on tablets and desktop, but when I try on iPhone it is not downloading any file. Please help

ie11 Downloading Base64 documents

I have tried pretty much everything at this point and I cannot get anything to work in ie.
I need ie to download base64 documents from an attachment panel. I have no access to the server side code or database. The images cannot be stored in a folder to be pulled up, they need to be presented this way.
I have tried using a plain link and sticking the base64 sting in there and it just opens up a new blank window.
<a target="_blank" download class="btn btn-primary downloadAttachment" href="' + blobUrl + '" >Download</a>
I have tried turning the url into a blob and opening the blob and that resulted in the browser not doing anything.
function base64toBlob(base64Data, contentType) {
contentType = contentType || '';
var sliceSize = 1024;
var byteCharacters = base64Data;
var bytesLength = byteCharacters.length;
var slicesCount = Math.ceil(bytesLength / sliceSize);
var byteArrays = new Array(slicesCount);
for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
var begin = sliceIndex * sliceSize;
var end = Math.min(begin + sliceSize, bytesLength);
var bytes = new Array(end - begin);
for (var offset = begin, i = 0 ; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
I am completely and totally stuck. I have tried everything from google and on here.
My two latest attempts here
https://jsfiddle.net/pqhdce2L/
http://jsfiddle.net/VB59f/464/
Some time ago I've coined this function to make ("offer/initialize") a download of an xlsx or csv content accepting both a Blob or a base64 string:
// Initializes a file download of a provided content
//
// Not usable outside browser (depends on window & document)
//
// #param {Blob|base64} cont File content as blob or base64 string
// #param {string} ftype File type (extension)
// #param {string} [fname='export.' + ftype] File name
// #param {string} [mime='application/zip'] File mime type
// #returns {void}
function makeFileDownload(cont, ftype, fname, mime) {
if (!fname) fname = 'export.' + ftype;
if (!mime) mime = ftype === 'csv' ? 'text/csv' : 'application/zip'; // or 'application/vnd.ms-excel'
if (Object.prototype.toString.call(cont) === '[object Blob]'
&& window.navigator && window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(cont, fname);
}
else {
var downloadLink = document.createElement('a');
downloadLink.download = fname;
downloadLink.href = typeof cont === 'string'
? 'data:' + mime + ';base64,' + cont
: window.URL.createObjectURL(cont);
downloadLink.onclick = function(e) { document.body.removeChild(e.target); };
downloadLink.style.display = 'none';
document.body.appendChild(downloadLink);
downloadLink.click();
}
};
This should be able to accept both Blob and base64 string - you should get the idea how it's being done for either a Blob and a base64 string from the if/else block.
If passing it base64 string is problematic just convert it to a Blob first (as suggested for example in this SO question, this answer is specifically aimed at IE11). Adjust the mime defaults according to your expected usage.
I suppose you already have the content (Blob/base64), keep your original link (which I suppose is to be clicked by an user) a plain link or rather a button (i.e. without the download/href attributes), attach it a click event handler where you'll call the function and it should initialize the download for you:
document.querySelector('#originalLink').addEventListener('click', function () {
makeFileDownload(content, extension, filename, mimetype);
});
If you are trying to generate blob URL in IE, it will not work.
We have to download the file to local by using below code:
function printPdf(id) {
$.ajax({
url: 'url',
type: 'POST',
data: { 'ID': id },
success: function (result) {
var blob = pdfBlobConvesion(result.PdfUrl, 'application/pdf');
var isIE = /*#cc_on!#*/false || !!document.documentMode;
// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;
if (isIE || isEdge) {
window.navigator.msSaveOrOpenBlob(blob, "ProviderOfficePDF.pdf");
}
else {
var blobUrl = URL.createObjectURL(blob);
window.open(blobUrl, "_blank");
}
}
});
}
function pdfBlobConvesion(b64Data, contentType) {
contentType = contentType || '';
var sliceSize = 512;
b64Data = b64Data.replace(/^[^,]+,/, '');
b64Data = b64Data.replace(/\s/g, '');
var byteCharacters = window.atob(b64Data);
var byteArrays = [];
for ( var offset = 0; offset < byteCharacters.length; offset = offset + sliceSize ) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, { type: contentType });
return blob;
}
IE, in classic fashion, requires you to use a proprietary method for "saving" a blob.
msSaveBlob or msSaveOrOpenBlob is what you're looking for.
Instead of adding it as the href, add an onclick handler to your a tag and call navigator.msSaveBlob(blob, "Sample Name");
Additionally if you need to support other browsers you'll need some other code to support those browsers.
For example:
var content = new Blob(["Hello world!"], { type: 'text/plain' });
var btn = document.getElementById('btn');
if (navigator.msSaveBlob) {
btn.onclick = download;
} else {
btn.href = URL.createObjectURL(content);
btn.download = true;
}
function download() {
if (navigator.msSaveBlob) {
navigator.msSaveBlob(content, "sample.txt");
}
}
<a id="btn" href="#">Download the text!</a>
var data = item;
var fileName = name;
if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE
workaround
var byteCharacters = atob(data);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], {type: 'application/octet-stream'});
window.navigator.msSaveOrOpenBlob(blob, fileName);
}
else if( agent.indexOf('firefox') > -1)
{
console.log(extention,'item111')
var byteCharacters = atob(data);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
//var FileSaver = require('file-saver');
var blob = new Blob([byteArray], {type: "application/octet-stream"});
saveAs(blob, fileName);
}
else{
this.fileDownload='data:application/octet-stream;base64,'+item;
var link = document.createElement("a");
const fileName=name;
link.href = this.fileDownload;
link.download=fileName;
link.click();
}
}

Download image from image tag with background color

Hi I am having proble while downloading the image from image tag, I have googled it but not getting any valid solutions. Can anyone help to get solve this..
Actually I am binding some bytestring to the image tag src like this
<img src="' + this.el.toDataURL("image/png") +'" class="img-responsive imgSmall" style="background-color:green;" alt="img" data-position-to="origin" data-transition="slide" id="signPrevwID_' + signatureid +'">
and I am downloading the the same image with background color green but its not working,everytime its saving with background color black only, for downloading Im using this code
var bannerImage = document.getElementById('signPrevwID_' + signatureid );
var imgData = getBase64Image(bannerImage);
console.log("imgData - "+imgData);
//alert("imgData - "+imgData);
var newName = 'Test_' + new Date().getTime()+".png";
var fileWritter = new AppUtils.FileWritter(newName);
fileWritter.saveBase64ToBinary(imgData, function(r){
console.log("saveBase64ToBinary() file saved");
}, function(e){
console.log("saveBase64ToBinary() file not saved");
});
var AppUtils2 = (function(){
//alert("AppUtils2");
// get the application directory. in this case only checking for Android and iOS
function localFilePath(filename) {
if(device.platform.toLowerCase() === 'android') {
return cordova.file.externalRootDirectory + filename;
} else if(device.platform.toLowerCase() == 'ios') {
return cordova.file.externalRootDirectory + filename;
}
}
// FileWritter class
function FileWritter(filename) {
//deleteStoredFromDevice(filename);
this.fileName = filename;
this.filePath = localFilePath(filename);
alert("fileName - "+fileName);
}
// decode base64 encoded data and save it to file
FileWritter.prototype.saveBase64ToBinary = function(data, ok, fail) {
var byteData = atob(data);
var byteArray = new Array(byteData.length);
for (var i = 0; i < byteData.length; i++) {
byteArray[i] = byteData.charCodeAt(i);
}
var binaryData = (new Uint8Array(byteArray)).buffer;
// createDirectory();
this.saveFile(binaryData, ok, fail);
}
// save file to storage using cordova
FileWritter.prototype.saveFile = function(data, ok, fail) {
this.fileData = data;
var path = this.filePath.substring(0, this.filePath.lastIndexOf('/'));
//console.log("saveFile() path - "+path);
var that = this;
// Write file on local system
window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory+"Download/Mobitrac/Docs", function(directoryEntry) {
var options = {create: true, exclusive: false};
alert("that.fileName - "+cordova.file.externalRootDirectory+"Download/Mobitrac/Docs");
directoryEntry.getFile(that.fileName, options, function(file) {
alert("that.fileName - "+that.fileName);
file.createWriter(function(writer) {
writer.onwriteend = function(event) {
if(typeof ok === 'function') {
alert("onwriteend");
//viewing documents locally
//var fileWritter = new AppUtils.viewFile(subEventId+'.'+fileExtention);
ok(event);
}
};
writer.write(that.fileData);
}, fail);
}, fail);
}, fail);
};
/*// open InApp Browser to view file
function viewFile(filename) {
//var path = localFilePath(filename);
var path = cordova.file.externalRootDirectory+"Download/Mobitrac/Docs/"+filename;
alert("viewFile() path - - "+path);
window.open(path, "_system", "location=yes,hidden=no,closebuttoncaption=Close");
}
return {
FileWritter: FileWritter,
localFilePath: localFilePath,
viewFile: viewFile
}*/
})();
var fileExtention = '';
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
console.log("data - "+dataURL);
return dataURL.replace(/^data:image\/(png);base64,/, "");
}
Byte string im getting with sketch.js canvas element, I mean Im drawing something on canvas and appening same image to the img tag in html with background color green.
I am not getting from where its breaking, please anybody help me

Canvas to .jpg file with Cordova Phonegap

I'm trying to store a canvas in my divice, reading in internet i found that i have to convert my canvas to Base64, nice, i did it...
Then i searched a function to store a base64 with cordova and just found a function that stores a Blob object, so i searched again and found a function that converts my base64 to Blob, and nice again, it apparently works, but when i go to the file explorer i'm just getting a file that says in plain text (and changing its extension to .txt ):
[object Uint8Array][object Uint8Array]
This is my final code:
function draw() {
window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) {
console.log('file system open: ' + fs.name);
getSampleFile(fs.root);
}, errorHandler);
}
function getSampleFile(dirEntry) {
var canvas = document.getElementById("mycanvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
//...some code to customize the canvas
//var mURI = canvas.toDataURL();
var mURI = canvas.toDataURL().replace(/data:image\/png;base64,/,'');
var x = Math.floor((Math.random() * 100000) + 1);
saveFile(dirEntry, b64toBlob(mURI,"image/png","512") , x+".png");
}
}
function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
console.log('Estoy en B64');
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
console.log('ByteArrays'+byteArrays);
var blob = new Blob(byteArrays, {type: contentType});
return blob;
}
function saveFile(dirEntry, fileData, fileName) {
console.log('1. DIRENTRY:'+dirEntry+', 2 FILEDATA:'+fileData+',3 FILENAME:'+fileName);
dirEntry.getFile(fileName, { create: true, exclusive: false }, function (fileEntry) {
writeFile(fileEntry, fileData);
}, errorHandler);
}
function writeFile(fileEntry, dataObj, isAppend) {
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function() {
console.log("Successful file write...");
};
fileWriter.onerror = function(e) {
console.log("Failed file write: " + e.toString());
};
fileWriter.write(dataObj);
});
}
I hope you can help me, the main goal of this is to store a picture with a watermark, so if you have another idea please tell me, thanks
Since you need to add a water mark you may refer following links
W3School Link
Jsfiddle Link
EDITED
var yourCanvas = document.getElementById('yourCanvasId');
var context = yourCanvas.getContext('2d');
var waterMarkImg = document.getElementById("waterMarkImageId");
context.drawImage(waterMarkImg, 0, 0, yourCanvas.width, yourCanvas.height);
var basse64 = yourCanvas.toDataURL();

Create a file with data ur

I have something like this.
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKQAAACkCAYAAAAZtYVBAAAgAElEQ…TFHIWRhe2sii/S5zA+N/ZF6gI+RiSKspPUBiI1UQf9/wDVxYvlSggfZqgAAAABJRU5Erkaa==="
Is there a way to create a file object? with this?
i see the method URL.createObjectURl but it seems like a need to create a blobl object and i dont really know how.
The following function will convert a data URI to a blob.
function dataURIToBlob(dataURI) {
// Split the dataUri up into parts
// data:[<mediatype>][;<charset>],(data)
var parts = /data:([^;]+)(?:;([^,]+))?,(.+)/.exec(dataURI),
mime = parts[1],
charset = parts[2] || 'charset=US-ASCII',
encodedData = parts[3];
var data;
if (charset === 'base64') {
// If base64 convert to a Uint8 clamped array of character codes
var decodedData = atob(encodedData);
data = new Uint8Array(decodedData.length);
for (var i = 0; i < decodedData.length; i++) {
data[i] = decodedData.charCodeAt(i);
}
} else {
data = decodeURIComponent(encodedData);
}
return new Blob([data], {
type: mime
});
}
You can see it working in this snippet which takes a data URI, converts it into a blob, then creates a blob URI that you can use to access the file. A sample image and CSV file is provided.
testData = {};
testData['image/gif'] = 'data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7';
testData['text/csv'] = 'data:text/csv;charset=utf-8,ID%2CScore%2CAssignee%2CCreated%2CComment%0Aid_value0%2Cscore_value0%2Cassignee_value0%2Ccreated_value0%2Ccomment_value0%0Aid_value1%2Cscore_value1%2Cassignee_value1%2Ccreated_value1%2Ccomment_value1%0Aid_value2%2Cscore_value2%2Cassignee_value2%2Ccreated_value2%2Ccomment_value2%0A';
function dataURIToBlob(dataURI) {
// Split the dataUri up into parts
// data:[<mediatype>][;<charset>],(data)
var parts = /data:([^;]+)(?:;([^,]+))?,(.+)/.exec(dataURI),
mime = parts[1],
charset = parts[2] || 'charset=US-ASCII',
encodedData = parts[3];
var data;
if (charset === 'base64') {
// If base64 convert to a Uint8 clamped array of character codes
var decodedData = atob(encodedData);
data = new Uint8Array(decodedData.length);
for (var i = 0; i < decodedData.length; i++) {
data[i] = decodedData.charCodeAt(i);
}
} else {
data = decodeURIComponent(encodedData);
}
return new Blob([data], {
type: mime
});
}
function createBlobURI() {
var blob = dataURIToBlob(dataURIInput.value);
var blobURI = URL.createObjectURL(blob);
blobURIAnchor.href = blobURI;
blobURIAnchor.innerHTML = blobURI;
blobURIAnchor.style.display = 'block';
blobURIAnchor.download = 'blob.' + blob.type.split('/')[1];
}
function insertTestData(mime) {
dataURIInput.value = testData[mime];
}
insertTestData('image/gif');
<button onclick="insertTestData('image/gif')">Image test</button>
<button onclick="insertTestData('text/csv')">CSV test</button>
<input id="dataURIInput" type="text"/>
<button onclick='createBlobURI()'>Create blob URI</button>
<a id="blobURIAnchor" href="#" style="display:none"></a>

Categories