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;
}
Related
I am new to coding in javascript, I have been tasked as an excersise using some pre-existing functions to create an image item using a given url. I need to read the image, store it in local storage and then display it on the screen. The only functionI need to add too is process file. I am stuck and cannot get it to display the image. I get an error saying that the path does not exist. Below is my code, any guidance to what I am doing wrong? I feel like I am very close but doing something funamendatly wrong.
function addImageEntry(key, url) {
var imgElement = new Image();
imgElement.alt = "Photo entry";
imgElement.src = url;
addSection(key, imgElement);
}
function makeItem(type, data) {
var itemObject = { type: type, data: data };
return JSON.stringify(itemObject);
}
function processFile(event) {
function addImage(url) {
var key = "diary" + Date.now();
addImageEntry(key, url);
var imgElement = new Image();
imgElement.src = url;
var item = makeItem("image", imgElement.src);
localStorage.setItem(key, item);
}
var inputElement = event.target;
var fileObject = inputElement.files[0];
var reader = new FileReader();
reader.addEventListener("load",addImage);
url = reader.readAsDataURL(fileObject);
event.target.value = "";
}
The url = reader.readAsDataURL(fileObject) won't store the image data.
It stores in reader.result.
Use imgElement.src = reader.result.
document.querySelector('input[type="file"]').addEventListener('change', processFile)
function processFile(event) {
var fileObject = event.target.files[0]
var reader = new FileReader()
reader.addEventListener('load', addImage)
reader.readAsDataURL(fileObject)
function addImage() {
var imgElement = new Image()
imgElement.src = reader.result
document.body.append(imgElement)
}
}
Amend:
function addImage(event) {
// use reader.result is ok too
localStorage.setItem('myimage', event.target.result)
}
function addImageEntry() {
var imgElement = new Image()
imgElement.src = localStorage.getItem('myimage')
imgElement.style.display = 'block'
document.body.append(imgElement)
}
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
function upload(file){
var reader = new FileReader();
reader.onload = function (evt) {
uploadComplet(file.name, evt.target.result);
}
reader.readAsBinaryString(file.fileBlob);
}
function downloadComplet(binaryString){
var newFile = new File( [binaryString] , "newName.jpg");
var downloadUrl = URL.createObjectURL(newFile);
var downloadButton = document.createElement('a');
downloadButton.setAttribute('href', downloadUrl);
downloadButton.setAttribute('download', newFile.name);
downloadButton.setAttribute('class', 'button');
downloadButton.innerText = 'Download: ' + newFile.name;
downloadButton.click();
}
I uploaded the BinaryString of the image file and downloaded it as it was. But I could not bring in the correct image. What should I do?
Take this as an example:
var img = document.createElement('img');
img.src = 'data:image/jpeg;base64,' + btoa('your-binary-data');
document.body.appendChild(img);
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
(I'm testing with Protractor and Jasmine, and I've also included image-diff and node-canvas in my project.)
I need to compare two images and make sure they are the same. One is saved in my file structure and the other is created from canvas. I am able to convert the canvas to image and also load the image from the file. Here's what I have:
var imagediff = require('../node_modules/js-imagediff/js/imagediff.js');
var Canvas = require('canvas');
var fs = require('fs');
var path = require('path');
beforeEach(function () {
jasmine.addMatchers(imagediff.jasmine);
});
function loadImage (url, callback) {
var image;
fs.readFile(url, function (error, data) {
if (error) throw error;
image = new Canvas.Image();
image.onload = function () {
callback(image);
};
image.src = data;
});
return image;
}
it('should work', function () {
//executeScript is needed to get the canvas element and convert it
browser.driver.executeScript(function() {
var can = document.querySelector('#workspace-canvas');
var ctx = can.getContext("2d");
var data = can.toDataURL("image/png");
var img = new Image();
img.src = data;
//this code below shows that the image was converted properly
// var link = document.createElement('a');
// link.href = img.src;
// link.download = 'image1.png';
// link.click();
return data;
}).then(function(result) {
newData = result;
var imgPath = path.join(__dirname, './images/image1.png');
loadImage(imgPath, function(image) {
console.log('loadImage');
var canvas = new Canvas();
canvas.width = image.width;
canvas.height = image.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0);
var data = canvas.toDataURL("image/png");
oldData = data;
//TODO: do a comparison here!
done();
});
});
My question is how do I compare the two images and make sure they are the same? I thought comparing the data URI would work but it doesn't. I'd really like to use image-diff but I'm not sure how to do that. Please help me!
The API of imagediff, has the imagediff.equal(a,b) function, that gets 2 Image objects, which should help you in this case.
If this won't help you, you could always md5 hash both of them and make sure the checksums are equal, more info on this md5, checksum.
Here's how I ended up doing it. I used fs.writeFile to save the new image to my project and then load that image and compare both images with image-diff.
var imagediff = require('../node_modules/js-imagediff/js/imagediff.js');
var Canvas = require('canvas');
var fs = require('fs');
var path = require('path');
beforeEach(function () {
jasmine.addMatchers(imagediff.jasmine);
});
function loadImage (url, callback) {
var image;
fs.readFile(url, function (error, data) {
if (error) throw error;
image = new Canvas.Image();
image.onload = function () {
callback(image);
};
image.src = data;
});
return image;
}
function writeFile (buffer, fileName) {
fs.writeFile(fileName, buffer, function (err) {
if(err) { console.log('ERROR', err); }
});
}
function dataURItoBuffer (dataURI, fileName) {
var byteString = dataURI.split(',')[1];
var buffer = new Buffer(byteString, 'base64');
writeFile(buffer, fileName);
}
it('should work', function () {
//fileName is defined somewhere else
var filePath = './images' + fileName + '.png';
//executeScript is needed to get the canvas element and convert it
browser.driver.executeScript(function() {
var can = document.querySelector('#workspace-canvas');
var ctx = can.getContext("2d");
var data = can.toDataURL("image/png");
return data;
}).then(function(result) {
dataURItoBuffer(result, fileName);
var oldImagePath = path.join(__dirname, './images/' + fileName + '.png');
var newImagePath = path.join(__dirname, filePath);
loadImage(oldImagePath, function(image) {
image1 = image;
loadImage(newImagePath, function(image){
image2 = image;
expect(imagediff.equal(image1, image2, 50)).toBeTruthy(); // 50 pixel tolerance
done();
});
});
});
});