Determine the dimensions of image from dataURI - javascript

I'm allowing users to load their own image file from file system according to this post (last part - Images from the local file system)
https://stackoverflow.com/a/20285053
My Code
handleFiles: function (evt) {
var file = evt.target.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = function (e) {
var contents = e.target.result;
console.log(contents);
//apply contents to src of img element
};
},
After getting the dataUri, I want to display the image on screen, however some images are bigger than the area in which I'm displaying them. Is there a way to check the size of the image given the dataUri (width and height) and resize is accordingly?
I am placing the dataUri in the 'src' attribute of image tag.

You can simply create an element in memory and read the value from it. Assuming "contents" is the dataURI of the image
handleFiles: function (evt) {
var file = evt.target.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = function (e) {
var contents = e.target.result;
console.log(contents);
var memoryImg = document.createElement('img');
memoryImg.src = contents;
var width = memoryImg.width;
var height = memoryImg.height;
};
},
The element will be cleaned up as soon as the interpreter finishes your function.

Related

Storing the canvas as a image with .png extension but in a variable

I have two Webpages, one in which a user draws on the canvas and can download it as an image, the second webpages the image can be uploaded to be further processed. is there a way to remove this downloading and again uploading and do the whole process in a single step?
The second page requires an image with an extension of PNG
I tried using canvas.toDataURL but its not working
Update
i have added the functionality of the second webpage to the first
can i directly save the canvas in the same format when an image is uploaded
this is the function to upload the file on the second webpage
function handleFileSelect(evt) {
const file = evt.target.files[0];
// do nothing if no file is selected
if (file == null) {
postData.data = '';
postData.type = '';
return;
}
// only allow images
if (!file.type.match('image.*')) {
alert('Unsupported Image File');
resetForm();
return;
}
const reader = new FileReader();
reader.onload = (event) => {
postData.data = event.target.result;
postData.type = file.type;
};
// Read in the image file as binary string.
reader.readAsBinaryString(file);
}
how can i convert the canvas in the result to "event.target.result"

Why is this FileReader onload not firing?

I am starting with this working JavaScript code:
// Begin File Open Code.
function fileOpen()
{
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('iDisplay');
fileInput.addEventListener('change', function(e)
{
file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType))
{
var reader = new FileReader();
reader.onload = function(e)
{
iDisplay.innerHTML = "";
image = new Image();
image.src = reader.result;
image.id = "I"; // Add an id attribute so the image editor code can access the image.
iDisplay.appendChild(image);
image.onload = function()
{
c = document.getElementById("canvas1");
context = c.getContext("2d");
c.width = image.width;
c.height = image.height;
context.drawImage(image,0,0);
}
}
reader.readAsDataURL(file);
moreFiles++;
document.getElementById("fileInput").disabled = true;
document.getElementById("fileInputD").innerHTML = '<p>Please refresh page to open a new image</p>';
}
else
{
iDisplay.innerHTML = "File type not supported."
}
});
}
// End File Open Code
And trying to break it up into two separate functions, fileOpen() and loadImage(). The reason is that loadImage will also be used to load default images. I came up with several non-working versions. After reading about the topic here, most recently this answer Javascript FileReader onload not firing I adjusted the code as follows:
// Begin File Open Code
function fileOpen(radio)
{
fileInput = document.getElementById('fileInput');
fileDisplayArea = document.getElementById('iDisplay');
fileInput.addEventListener('change', function(e)
{
file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType))
{
reader = new FileReader();
reader.onload = fileSelected;
function fileSelected(e)
{
iDisplay.innerHTML = "";
image = new Image();
image.src = reader.result;
image.id = "I"; // Add an id attribute so the image editor code can access the image.
iDisplay.appendChild(image);
image.onload = loadImage();
}
}
else
{
iDisplay.innerHTML = "File type not supported."
}
})
}
// End File Open Code
// Begin Load Image Code - This will be used to load a preselected image
function loadImage()
{
c = document.getElementById("canvas1");
context = c.getContext("2d");
c.width = image.width;
c.height = image.height;
context.drawImage(image,0,0);
reader.readAsDataURL(file);
document.getElementById("fileInput").disabled = true;
document.getElementById("fileInputD").innerHTML = '<p>Please refresh page to open a new image</p>';
}
// End Load Image Code
But, after reviewing in the Chrome Inspector, the code never gets past
reader.onload = fileSelected;
After that line, the function exits, and nothing is loaded. I have spent hours on variations of this code and cannot get it to fire past that line. So, my question is "why?" I should note that I want to stay with pure JavaScript.
Thank you in advance.
There appears to be a bug in Chrome 73 where it isn't fired if you have a debugger statement.
I literally have
reader.readAsText(blob);
debugger;
and it never hits the onload
If I change it to
debugger;
reader.readAsText(blob);
then it works.
Fixed by Chrome 75.
You can also use FileReader.readAsDataURL() to parse the file from your . This will create a string in memory containing a base64 representation of the image.
<input type="file" accept="image/*" onchange="loadFile(event)">
<img id="output"/>
<script>
var loadFile = function(event) {
var reader = new FileReader();
reader.onload = function(){
var output = document.getElementById('output');
output.src = reader.result;
};
reader.readAsDataURL(event.target.files[0]);
};
</script>
Ref: Preview an image before it is uploaded

Uploading an image from computer to Fabric.JS Canvas

Are there any Fabric.JS Wizards out there?
I've done my fair research and I can't seem to find much of an explanation on how to add an image to the fabric.JS canvas.
User Journey:
a) User uploads an image from an input file type button.
b) As soon as they have selected an image from their computer I want to place it into the users canvas.
So far I've got to storing the image into an expression, this is my code below:
scope.setFile = function(element) {
scope.currentFile = element.files[0];
var reader = new FileReader();
/**
*
*/
reader.onload = function(event) {
// This stores the image to scope
scope.imageSource = event.target.result;
scope.$apply();
};
// when the file is read it triggers the onload event above.
reader.readAsDataURL(element.files[0]);
};
My HTML/Angular:
<label class="app-file-input button">
<i class="icon-enter"></i>
<input type="file"
id="trigger"
onchange="angular.element(this).scope().setFile(this)"
accept="image/*">
</label>
If you haven't guessed yet I am using a MEAN stack. Mongoose, Express, Angular and Node.
The scope imageSource is what the image is store in. I've read this SO
and it talks about pushing the image to the Image object with my result, and then pass it to the fabric.Image object. Has anyone done a similar thing that they can help me with?
Thanks in advance
**** UPDATE ****
Directive defines the canvas variable:
var canvas = new fabric.Canvas(attrs.id, {
isDrawingMode: true
});
Upload image from computer with Fabric js.
var canvas = new fabric.Canvas('canvas');
document.getElementById('file').addEventListener("change", function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (f) {
var data = f.target.result;
fabric.Image.fromURL(data, function (img) {
var oImg = img.set({left: 0, top: 0, angle: 00,width:100, height:100}).scale(0.9);
canvas.add(oImg).renderAll();
var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({format: 'png', quality: 0.8});
});
};
reader.readAsDataURL(file);
});
canvas{
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<input type="file" id="file"><br />
<canvas id="canvas" width="450" height="450"></canvas>
once you have a dataURL done, you can do either:
reader.onload = function(event) {
// This stores the image to scope
fabric.Image.fromURL(event.target.result, function(img) {
canvas.add(img);
});
scope.$apply();
};
Or you put on your image tag an onload event where you do:
var img = new fabric.Image(your_img_element);
canvas.add(img);
This is for drag and drop from desktop using the dataTransfer interface.
canvas.on('drop', function(event) {
// prevent the file to open in new tab
event.e.stopPropagation();
event.e.stopImmediatePropagation();
event.e.preventDefault();
// Use DataTransfer interface to access the file(s)
if(event.e.dataTransfer.files.length > 0){
var files = event.e.dataTransfer.files;
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (f.type.match('image.*')) {
// Read the File objects in this FileList.
var reader = new FileReader();
// listener for the onload event
reader.onload = function(evt) {
// put image on canvas
fabric.Image.fromURL(evt.target.result, function(obj) {
obj.scaleToHeight(canvas.height);
obj.set('strokeWidth',0);
canvas.add(obj);
});
};
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
}
});
Resources
https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/File_drag_and_drop

Saving image bytes into hidden field HTML5

I am using following code to upload the image
$selectFile = $('<input type="file">').click();
$selectFile.change(function (e) {
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
$div.append('<figure class="images"><img src="'+ event.target.result +'" draggable="true" alt=""></figure>');
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
});
When I look at the event.target.result it contains something like data:image/jpeg;base64,/9j/4AAQSkZJRgAB
I am not sure if these are the image bytes? I am not very much familiar with HTML 5.
How do I get the image bytes so that i can store them into some hidden field.
The data after the "data:image/jpeg;base64," is a Base64 encoded version of the image. You can convert it to a byte array using:
var byteCharacters = atob(b64Data);
But I'm not sure why you'd want to, when the Base64 is fine for rendering an image anyway with :
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgAB...." >

how to add scroll to my WinJS app VS2012

I have a metro app (WinJS) in VS2012 which loads an image inside a by using an a from my local disk like which next function
function loadPictureFromFile(event) {
var selectedFile = event.target.files[0];
var reader = new FileReader();
imageElement = document.createElement("img"); //creates <img id="img"> element
imageElement.title = selectedFile.name; //set photo's name
reader.onload = function (event) {
imageElement.setAttribute("src", event.target.result); //picture's source
_divPicture.appendChild(imageElement); //Add's <img> element to Div element
};
reader.readAsDataURL(selectedFile);
}
but sometimes my image is too big to display on screen, it requires a scroll for viewing it completely, how to add it from javascript or WinJS after loading picture??
in your default.css simply add
body {
overflow-x:auto;
overflow-y:auto;
}

Categories

Resources