Convert an Image DataUrl to Blob in JavaScript with Webkit Fallback? - javascript

I have an image represented as data URL. I want this image to be converted into a blob.
I use the following method for this purpose:
function dataURItoBlob(dataURI) {
// convert base64 to raw binary data held in a string
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var arrayBuffer = new ArrayBuffer(byteString.length);
var _ia = new Uint8Array(arrayBuffer);
for (var i = 0; i < byteString.length; i++) {
_ia[i] = byteString.charCodeAt(i);
}
var dataView = new DataView(arrayBuffer);
var blob = new Blob([dataView], { type: mimeString });
return blob;
}
This function is working but as I found here: Blob support the blob sometimes need the webkit prefix to work. I know that for URL I could use the fallback with
var _URL = URL || webkitURL;
How do I have to include the webkit prefix version as a fallback for older browsers in my function? Do I have to use BlobBuilder() instead on Blob()?

Best way to feature detect support for Blob is try and catch
function supportsBlob() {
try {
return !!new Blob();
} catch (e) {
return false;
}
}

Related

File is not a constructor issue in angular 9

I am trying to crop image using the angular library "ngx-image-cropper". Thereafter cropping, I am getting an image in the base64 format so I want to convert that image to file format. I am using the following code to convert base64 string to BLOB and then BLOB to file format.
fileChangeEvent(event: any): void {
this.imageChangedEvent = event;
}
imageCropped(event: ImageCroppedEvent) {
this.croppedImage = event.base64;
var result = this.b64toBlob(this.croppedImage);
var file = new File([result], 'uploaded_file.jpg', {type: 'image/jpeg', lastModified: Date.now()});
}
b64toBlob(dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], { type: 'image/jpeg' });
}
But on BLOB to file conversion I am getting error "ERROR TypeError: File is not a constructor". What should I do to resolve this issue?
Thanks in advance.
I was facing the same problem and I have fixed it after removing the File type from the component variable.
public imageFile: File = null;
The solution works for me:
public imageFile = null;

Error Converting Base64 data to File using JavaScript on Internet Explorer(0x800a01bd - JavaScript runtime error: Object doesn't support this action)

I am trying to convert base64 data to file using javascript on asp.net, but i am getting( 0x800a01bd - JavaScript runtime error: Object doesn't support this action) error on final stage while converting blob to file at final stage.
Here is my code:
function dataBaseURLtoFile(str) {
// extract content type and base64 payload from original string
var pos = str.indexOf(';base64,');
var type = str.substring(5, pos);
var b64 = str.substr(pos + 8);
// decode base64
var imageContent = atob(b64);
// create an ArrayBuffer and a view (as unsigned 8-bit)
var buffer = new ArrayBuffer(imageContent.length);
var view = new Uint8Array(buffer);
// fill the view, using the decoded base64
for (var n = 0; n < imageContent.length; n++) {
view[n] = imageContent.charCodeAt(n);
}
// convert ArrayBuffer to Blob
var blob = new Blob([buffer], { type: type });
//convert blob to file
var file = new File([blob], "name", { type: "image/jpeg", });
return file;
}
I try to check your code and found that issue is on line below.
var file = new File([blob], "name", { type: "image/jpeg", });
IE and Edge browser does not supports the File() constructor.
File.File() constructor
For IE and Edge browser you need to use any alternative way.
You can try to refer thread below may give you some helpful information about alternative ways.
Is there an alternative for File() constructor for Safari and IE?

Angular 2 Image resize before upload

Im looking to resize an image before it is uploaded to a server, at the moment i am using ng2-imageupload like this:
<input id="media" class="inputfile" type="file" name="media" image-upload
(imageSelected)="selected($event)"
[resizeOptions]="resizeOptions" (change)="onChange($event)">
export class WpMediaFormComponent {
file: File;
resizeOptions: ResizeOptions = {
resizeMaxHeight: 768,
resizeMaxWidth: 438
};
selected(imageResult: ImageResult) {
console.log(imageResult);
this.dataBlob = this.dataURItoBlob(imageResult.resized.dataURL);
let blob = this.dataURItoBlob(imageResult.resized.dataURL);
}
This then returns an object, like this:
dataURL:"data:image/jpeg;base64, DATA URI HERE"
type:"image/jpeg;"
I can then convert this object to a blob using this function:
dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = decodeURI(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
Before doing this I was uploading the image to the server using this code:
onChange(event: EventTarget) {
let eventObj: MSInputMethodContext = <MSInputMethodContext> event;
let target: HTMLInputElement = <HTMLInputElement> eventObj.target;
let files: FileList = target.files;
this.file = files[0];
console.log(this.file);
//this.update.emit(this.file);
}
Does anyone have idea how I can feed the blob returned from dataURItoBlob method into the file upload onChange event?
Im a little lost here.
So I figured it out with the help of #Brother Woodrow, and this thread:
How to convert Blob to File in JavaScript
Here is my updated code, not the only thing I had to change was the selected method:
selected(imageResult: ImageResult) {
// create a blob
let blob: Blob = this.dataURItoBlob(imageResult.resized.dataURL);
// get the filename
let fileName: string = imageResult.file.name;
// create a file
this.file = new File([blob], fileName);
console.log(this.file);
// event emitter send to container then to http post
this.update.emit(this.file);
}
I can now upload 3MB and they are pushed to the server around 150kB in seconds which is great for the user especially as this app will mostly be used by mobile devices.
You'll need to convert the Data URI to a Blob, then send that back to your server. This might be helpful: Convert Data URI to File then append to FormData
Once you have the blob, it should be easy enough to use FormData and the Angular HTTP class to upload it to your server for further processing.
let formData = new FormData();
formData.append(blob);
this.http.post('your/api/url', fd).subscribe((response) => console.log(reponse);

How Might I Upload an Image Previously Stored in LocalStorage?

I have an html5 mobile web app (http://app.winetracker.co) and I'm working on feature that remembers user's state when they come back to the app in their browser (which always automatically refreshes in iOS safari). I'm storing the URL and form-field data via local storage. One of the form field data items is an file-input for images. I am successfully converting images to a base64 via canvas and storing it to localStorage.
function storeTheImage() {
var imgCanvas = document.getElementById('canvas-element'),
imgContext = imgCanvas.getContext("2d");
var img = document.getElementById('image-preview');
// Make sure canvas is as big as the picture BUT make it half size to the file size is small enough
imgCanvas.width = (img.width/4);
imgCanvas.height = (img.height/4);
// Draw image into canvas element
imgContext.drawImage(img, 0, 0, (img.width/4), (img.height/4));
// Get canvas contents as a data URL
var imgAsDataURL = imgCanvas.toDataURL("image/png");
// Save image into localStorage
try {
window.localStorage.setItem("imageStore", imgAsDataURL);
$('.localstorage-output').html( window.localStorage.getItem('imageStore') );
}
catch (e) {
console.log("Storage failed: " + e);
}
}
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#image-preview').attr('src', e.target.result);
storeTheImage();
}
reader.readAsDataURL(input.files[0]);
}
}
$('.file-input').on('change', function() {
readURL(this);
});
see this jsFiddle: https://jsfiddle.net/tonejac/ceLwh9qp/19/
How might I convert the localStore image dataURL string back to an image file so I can upload it to my server?
How might I convert the localStore image dataURL string back to an image file
See your fiddle, Javascript pane line 25.
// recompose image :
var imgRecomposed = document.createElement('img');
$('.image-recomposed').append(imgRecomposed);
imgRecomposed.src = window.localStorage.getItem('imageStore');
We create an image element and fill the src attibute with the data of the stored 'dataImage'.
In your Fiddle:
// Save image into localStorage
try {
window.localStorage.setItem("imageStore", imgAsDataURL);
$('.localstorage-output').html( window.localStorage.getItem('imageStore') );
}
catch (e) {
console.log("Storage failed: " + e);
}
Place any of the following in your try/catch:
$('#canvas-element').context.drawImage(imgAsDataURL);
$('#canvas-element').context.drawImage(imgAsDataURL, 0, 0);
$('#canvas-element').replace(imgAsDataURL);
This will place the stored image into the Canvas you have displayed.
It is already an 'image' - you can use it as the src for an element etc. Sending it to your server is depends on the environment you have - basically an Ajax POST or similar sending the base64 string?.
You will first have to convert this dataURL to a blob, then use a FormData object to send this blob as a file.
To convert the dataURL to a blob, I do use the function from this answer.
function upload(dataURI, url){
// convert our dataURI to blob
var blob = dataURItoBlob(dataURI);
// create a new FormData
var form = new FormData();
// append the blob as a file (accessible through e.g $_FILES['your_file'] in php and named "your_filename.extension")
form.append('your_file', blob, 'your_filename.'+blob.type.split('image/')[1]);
// create a new xhr
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
// send our FormData
xhr.send(form);
}
// from https://stackoverflow.com/questions/4998908/convert-data-uri-to-file-then-append-to-formdata/5100158#5100158
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
var savedIntoLocalStorage = 'data:image/png;base64,...=';
// execute the request
upload(savedIntoLocalStorage, 'http://yourserver.com/upload.php');

Window.Open with PDF stream instead of PDF location

Based on the question Open PDF in new browser full window, it looks like I can use JavaScript to open a new window with a PDF file with the following code:
window.open('MyPDF.pdf', '_blank');
I'd like to do so on a return trip from the server by adding a byte array instead of the file name to use as the URL location in window.open
I'm currently returning PDF files like this:
Response.Clear();
Response.ContentType = "application/pdf";
Response.BinaryWrite(pdfByteArray);
Response.Flush();
Is there a way to open a new window with a PDF byte array in javascript.
Something like this:
var script = "window.open('" + pdfByteArray + "', '_blank');";
ScriptManager.RegisterClientScriptBlock(Parent.Page, typeof(Page), "pdf", script, true);
It looks like window.open will take a Data URI as the location parameter.
So you can open it like this from the question: Opening PDF String in new window with javascript:
window.open("data:application/pdf;base64, " + base64EncodedPDF);
Here's an runnable example in plunker, and sample pdf file that's already base64 encoded.
Then on the server, you can convert the byte array to base64 encoding like this:
string fileName = #"C:\TEMP\TEST.pdf";
byte[] pdfByteArray = System.IO.File.ReadAllBytes(fileName);
string base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);
NOTE: This seems difficult to implement in IE because the URL length is prohibitively small for sending an entire PDF.
Note: I have verified this in the latest version of IE, and other browsers like Mozilla and Chrome and this works for me. Hope it works for others as well.
if (data == "" || data == undefined) {
alert("Falied to open PDF.");
} else { //For IE using atob convert base64 encoded data to byte array
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
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/pdf'
});
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else { // Directly use base 64 encoded data for rest browsers (not IE)
var base64EncodedPDF = data;
var dataURI = "data:application/pdf;base64," + base64EncodedPDF;
window.open(dataURI, '_blank');
}
}
Adding to #Dinesh's answer to handle Not allowed to navigate top frame to data URL error in Chrome and Edge
if (data == "" || data == undefined) {
// Log Error: PDF data not available
} else {
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 file = new Blob([byteArray], { type: 'application/pdf;base64' });
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
// For IE
window.navigator.msSaveOrOpenBlob(file, 'mypdf.pdf');
} else {
// For non-IE
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
}

Categories