how to covert base64 string to file object in javascript? - javascript

I have to convert a base64 encoded string to file object in java script so that i can pass that object to php and access that object by FILE variable.
Here is my code:
$(document).delegate(':file', 'change', function () {
files = !!this.files ? this.files : [];
if (!files.length || !window.FileReader)
return; // no file selected, or no FileReader support
filenum = $(this).attr('data');
$("form#cropmodal #filenum").val(filenum);
var oMyForm = new FormData();
for (i = 0; i < files.length; i++) {
var ext = $("#ImgId" + filenum).val().split('.').pop().toLowerCase();
output_format = ext;
if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg']) == -1) {
alert('Invalid extension');
return false;
}
var mime_type = "image/jpeg";
if (typeof output_format !== "undefined" && output_format == "png") {
mime_type = "image/png";
}
var reader = new FileReader();
reader.readAsArrayBuffer(files[i]);
reader.onload = function (event) {
// blob stuff
var blob = new Blob([event.target.result]); // create blob...
window.URL = window.URL || window.webkitURL;
var blobURL = window.URL.createObjectURL(blob); // and get it's URL
// helper Image object
var image = new Image();
image.src = blobURL;
//preview.appendChild(image);
// preview commented out, I am using the canvas instead
image.onload = function () {
// have to wait till it's loaded
var cvs = document.createElement('canvas');
cvs.width = image.naturalWidth;
cvs.height = image.naturalHeight;
var ctx = cvs.getContext("2d").drawImage(image, 0, 0);
var newImageData = cvs.toDataURL(mime_type, 50 / 100);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
var cvs = document.createElement('canvas');
cvs.width = result_image_obj.naturalWidth;
cvs.height = result_image_obj.naturalHeight;
var ctx = cvs.getContext("2d").drawImage(result_image_obj, 0, 0);
var type = "image/jpeg";
var data = cvs.toDataURL(type);
data = data.replace('data:' + type + ';base64,', '');
var the_file = new Blob([window.atob(data)], {type: 'image/jpeg', encoding: 'utf-8'});
oMyForm.append("media[]", the_file);
oMyForm.append("_token", "{{ csrf_token() }}");
}
};
}
});
When i alert "the_file" it will show "Object Blob", but i need "Object File"

You can use like this:
base64 decode javascript

Related

createObjectURL() does not generate an appropriate image URL

I am using JavaScript to generate an image URL. When I opened the url generated, the image is just a small rectangle with black background, which is not the image I want at all. Hence, I am not sure where the problem is.
My response from the backend is:
filename=imageName, imageData = base64Image, dataUrl =
"data:image/gif;base64," + base64Image
str.split(':').pop().split(';')[0]; -> this line is equal to image/gif
axios.post('/convert/image', fd, {'Content-Type' : 'multipart/form-data'})
.then (res => {
// decoded = base64.decodebytes(res.data.imageData);
// console.log(decoded);
var encodedString = btoa(res.data.imageData);
// console.log(encodedString);
var decodedData = window.atob(encodedString);
var byteNumbers = new Array(decodedData.length);
for (var i = 0; i < decodedData.length; i++) {
byteNumbers[i] = decodedData.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var str = res.data.dataUrl;
var type = str.split(':').pop().split(';')[0];
var blob = new Blob([JSON.stringify(byteArray)], {type: type});
console.log(blob);
var e = document.createEvent('MouseEvents'),
a = document.createElement('a');
a.download = 'download';
var urlCreator = window.URL || window.webkitURL;
a.href = urlCreator.createObjectURL(blob);
a.dataset.downloadurl = [type, a.download, a.href].join(':');
console.log(a.dataset.downloadurl);
e.initEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
urlCreator.revokeObjectURL(a.href);
});

Saving Facebook profile picture (fetched from Facebook API) as file object using javascript

I want to save facebook profile image URL to file object I tried to convert it to base64 then convert it to file object but i want file object outside the function maybe it some sort of stupid question but any help? following what i tried
var imgUrl = 'https://dl.dropboxusercontent.com/s/4e90e48s5vtmfbd/aaa.png';
var convertImgToDataURLviaCanvas = function(url, callback) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL();
callback(dataURL);
canvas = null;
};
img.src = url;
}
convertImgToDataURLviaCanvas(imgUrl, function(base64_data) {
var byteString = atob(base64_data.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);
}
var blob = new Blob([ia], {
type: 'image/jpeg'
});
var file = new File([blob], "images.jpg");
console.log(file)
});
You can use global variable and assign file object to that variable inside your function.
basically split var file = new File([blob], "images.jpg");
into
var file = null; //outside convertImgToDataURLviaCanvas
file = new File([blob], "images.jpg"); //inside convertImgToDataURLviaCanvas

crop image with jcrop I get a black image when decode it in base64

I used a lot time, trying to get a successful decode image in base64, but I get a black image. I don't know what is wrong.
I am using jcrop
I need yo two thing.
Get a successful image when decode it base64 and I can rotate image before to crop. Appreciate your help or recommendations.
I am using this example is not mine in jisfidle
var cropCoords,
file,
uploadSize = 360,
previewSize = 500;
$("input[type=file]").on("change", function(){
file = this.files[0];
readFile(file, {
width: previewSize,
height: previewSize
}).done(function(imgDataUrl, origImage) {
$("input, img, button").toggle();
initJCrop(imgDataUrl);
}).fail(function(msg) {
alert(msg);
});
});
$("button[type=submit]").on("click", function(){
$(this).text("Uploading...").prop("disabled", true);
readFile(file, {
width: uploadSize,
height: uploadSize,
crop: cropCoords
}).done(function(imgDataURI) {
var data = new FormData();
var blobFile = dataURItoBlob(imgDataURI);
data.append('file', blobFile);
$.ajax({
url: "/upload",
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function() {
alert("Yay!");
},
error: function(xhr) {
alert("Well, obviously we can't upload the file here."+
"This is what the data looks like: " +
imgDataURI.substr(0,128)+"...");
console.log(imgDataURI);
}
});
});
});
/*****************************
show local image and init JCrop
*****************************/
var initJCrop = function(imgDataUrl){
var img = $("img.crop").attr("src", imgDataUrl);
var storeCoords = function(c) {
cropCoords = c;
};
var w = img.width();
var h = img.height();
var s = uploadSize;
img.Jcrop({
onChange: storeCoords,
onSelect: storeCoords,
aspectRatio: 1,
setSelect: [(w - s) / 2, (h - s) / 2, (w - s) / 2 + s, (h - s) / 2 + s]
});
};
/*****************************
Read the File Object
*****************************/
var readFile = function(file, options) {
var dfd = new $.Deferred();
var allowedTypes = ["image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/bmp"];
if ($.inArray(file.type, allowedTypes) !== -1) {
//define FileReader object
var reader = new FileReader();
var that = this;
//init reader onload event handlers
reader.onload = function(e) {
var image = $('<img/>')
.load(function() {
//when image is fully loaded
var newimageurl = getCanvasImage(this, options);
dfd.resolve(newimageurl, this);
})
.attr('src', e.target.result);
};
reader.onerror = function(e) {
dfd.reject("Couldn't read file " + file.name);
};
//begin reader read operation
reader.readAsDataURL(file);
} else {
//some message for wrong file format
dfd.reject("Selected file format (" + file.type + ") not supported!");
}
return dfd.promise();
};
/*****************************
Get New Canvas Image URL
*****************************/
var getCanvasImage = function(image, options) {
//define canvas
var canvas = document.createElement("canvas"),
ratio = {
x: 1,
y: 1
};
if (options) {
if (image.height > image.width) {
ratio.x = image.width / image.height;
} else {
ratio.y = image.height / image.width;
}
}
canvas.height = options.crop ? Math.min(image.height, options.height) : Math.min(image.height, Math.floor(options.height * ratio.y));
canvas.width = options.crop ? Math.min(image.height, options.width) : Math.min(image.width, Math.floor(options.width * ratio.x));
var ctx = canvas.getContext("2d");
if (options.crop) {
//get resized width and height
var c = options.crop;
var f = image.width / options.previewWidth;
var t = function(a) {
return Math.round(a * f);
};
ctx.drawImage(image, t(c.x), t(c.y), t(c.w), t(c.h), 0, 0, canvas.width, canvas.height);
} else {
ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height);
}
//convert canvas to jpeg url
return canvas.toDataURL("image/jpeg");
};
/*****************************
convert dataURI to blob
*****************************/
var dataURItoBlob = function(dataURI) {
var blob = window.Blob || window.WebKitBlob || window.MozBlob;
//skip if browser doesn't support Blob object
if (typeof blob === "undefined") {
alert("Oops! There are some problems with your browser! <br/>New image produced from canvas can\'t be upload to the server...");
return dataURI;
}
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs
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 an ArrayBuffer
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: mimeString
});
};
html
<input type="file" />
<img class="crop" style="display:none" />
<button type="submit" style="display:none">Upload</button>
I get a black image when decode it in base64
Example image
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDAQMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBD/wAARCABLAEsDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD8qqKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/2Q==

Listen for the statement until it's true

I'm looking for the solution to my problem with image upload. I have one script that is kind of compressing my files with Javascript. Then it creates an Array with results in base64 which I want to add to my page as an <input type="hidden">. I have just one problem. It takes a bit to compress these images and .change() event on file input is not enough. Because it begins before the compression is done.
I was thinking about adding something like event listener for the statement, something like:
if(result_base64.length != input.files.length){
listen
} else {
do the function
}
Is it possible to achieve that without setting the interval function?
The compression script:
var result_base64 = [];
var images = document.getElementById('images');
var max_width = images.getAttribute('data-maxwidth');
var max_height = images.getAttribute('data-maxheight');
images.onchange = function(){
if ( !( window.File && window.FileReader && window.FileList && window.Blob ) ) {
alert('The File APIs are not fully supported in this browser.');
return false;
}
readfiles(images.files);
}
function readfiles(files) {
for (var i = 0; i < files.length; i++) {
processfile(files[i]);
}
images.value = "";
}
function processfile(file) {
if( !( /image/i ).test( file.type ) ){
alert( "File "+ file.name +" is not an image." );
return false;
}
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function (event) {
var blob = new Blob([event.target.result]);
window.URL = window.URL || window.webkitURL;
var blobURL = window.URL.createObjectURL(blob);
var image = new Image();
image.src = blobURL;
image.onload = function() {
result_base64.push(resizeMe(image));
}
};
}
function resizeMe(img) {
var canvas = document.createElement('canvas');
var width = img.width;
var height = img.height;
if (width > height) {
if (width > max_width) {
height = Math.round(height *= max_width / width);
width = max_width;
}
} else {
if (height > max_height) {
width = Math.round(width *= max_height / height);
height = max_height;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
return canvas.toDataURL("image/jpeg",0.7);
}
Then it creates an Array with results in base64
In processFile() you can fire an event like
function processfile(file) {
if( !( /image/i ).test( file.type ) ){
alert( "File "+ file.name +" is not an image." );
return false;
}
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function (event) {
var blob = new Blob([event.target.result]);
window.URL = window.URL || window.webkitURL;
var blobURL = window.URL.createObjectURL(blob);
var image = new Image();
image.src = blobURL;
image.onload = function() {
result_base64.push(resizeMe(image));
$(window).trigger('filesCompressed', result_base64); // This is the addition
}
};
}
Where you need these files, you can listen for this event like
$(window).on('filesCompressed', function(e, files) {
// Do something with files
})
Catch: The listening code must execute before the event is triggered.

Creating a Blob from an external image url

I have an file input that i used to get a file and turn it into a blob. Is there anyway I can get an external image url and turn that into a blob? Here is the code I am using to do it with just a file from a <input type="file" />:
//Process the file and resize it.
function processfile(file) {
if (!(/image/i).test(file.type)) {
alert("File " + file.name + " is not an image.");
return false;
}
// read the files
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function (event) {
// blob stuff
var blob = new Blob([event.target.result]); // create blob...
window.URL = window.URL || window.webkitURL;
var blobURL = window.URL.createObjectURL(blob); // and get it's URL
// helper Image object
var image = new Image();
image.src = blobURL;
image.onload = function () {
for (var x = 0; x < self.ThumbSizes.length; x++) {
// have to wait till it's loaded
var resized = resizeMe(image, self.ThumbSizes[x]); // send it to canvas
var resized_blob = dataURItoBlob(resized);
uploadFile(resized_blob, self.ThumbSizes[x].Name);
}
}
};
Instead of passing a file through I wanted to be able to structure this code to pass a image url and convert it into a blob.
I hope it helps you. (I didn't run it.)
function processfile(imageURL) {
var image = new Image();
var onload = function () {
var canvas = document.createElement("canvas");
canvas.width =this.width;
canvas.height =this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
canvas.toBlob(function(blob) {
// do stuff with blob
});
};
image.onload = onload;
image.src = imageURL;
}

Categories

Resources