Is it possible to load an image into a web page locally? - javascript

The idea is to take an image from a user's machine and allow them to display the image in a webpage. I do not want to send the image back to the server.
An upload button will exist. It should just update the page content dynamically.
Can this be done with HTML5 localstorage or anything?

FileReader is capable of doing this. Here's sample code:
<input type="file" id="files" name="files[]" multiple />
<img id="image" />
<script>
function onLoad(evt) {
/* do sth with evt.target.result - it image in base64 format ("data:image/jpeg;base64,....") */
localStorage.setItem('image', evt.target.result);
document.getElementById('image').src = evt.target.result;
};
function handleFileUpload(evt) {
var files = evt.target.files; // FileList object
for (var i = 0; i < files.length; i++) {
var f = files[i];
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
reader.onload = onLoad;
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileUpload, false);
var image = localStorage.getItem('image');
if (image !== null) {
document.getElementById('image').src = image;
}
</script>

Yeah absolutely, providing you have a cutting edge browser (Chrome or Firefox).
You want to use FileReader and readAsDataURL(). Take a look at the third example in this tutorial:
http://www.html5rocks.com/en/tutorials/file/dndfiles/

Related

Losing quality in image when sending to back end

The user uploads a photo which is then edited and cropped using Croppie. The edited and cropped version is the one that needs to be saved in the back end.
The current code takes the edited image, saves it in the database though when fetched, it displays the edited image though it has lost colour/not showing colours (displayed below)
Image being sent:
Image fetched:
And here is the code:
<input id="uploadAvatar" type="file" name="file" accept="image/*" />
$('#uploadAvatar).on('change', function(){
var reader = new FileReader();
reader.onload = function (e) {
var blob = dataURItoBlob(e.target.result;);
var fd = new FormData();
fd.append("file", blob);
//SERVICE HANDLES THE HTTP REQUEST
httpUploadAvatarServ('../p3sweb/FileUploadServlet', fd, function (callback) {
console.log(callback)
});
}
}
function dataURItoBlob(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type: 'image/jpeg '});
}
Question
Why is it that the image is losing quality/colour?
I think your issue may be in the dataURItoBlob function. Here's how I go about getting the base64 data with croppie before sending it to the server. Tried to abridge my code for simplicity... Hopefully I didn't make it worse:
function PlaceLargeImg (input, imgId, zindex) {
var $imgel = $(imgId);
var reader = new FileReader();
reader.onload = function(e) {
// Sets preview image src to the value of file input.
$imgel.attr('src', e.target.result);
// Bind croppie
cropperlg.bind({
url: $imgel.attr('src')
});
// On click method which crops and sets results to html input.
$('.btn-crop-lg').on('click', () => {
cropperlg.result({
type: 'canvas',
size: {width: 1000, height: 400}
}).then(function(result) {
$('#base64lg').val(result); // Resulting cropped img base64 that gets sent to server.
$('#uploadLg').submit();
});
});
};
reader.readAsDataURL(input.files[0]);
}
EDIT: If your image looks good in a clint-side preview AFTER parsing through dataUritoBlob, then the issue is on the server. In this case, you'll need to post your server side code.

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"

Javascript Jigsaw with image upload

http://codepen.io/TheEnd/pen/mEzVAE
The link above is a jigsaw game i found on codepen. I wish to make the image that is the jigsaw to be an image uploaded by the user. So the jigsaw is an image they choose. I want to do this with Javascript i understand PHP may be easier but i want a javascript/jquery application. The code below is what i believe can solve this issue but i dont know how to implement it as a img src and bring both codes together any help would appreciated.
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
<script>
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
previewFile(); //calls the function named previewFile()
</script>

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

Uploaded Image does not show in Safari 5.1 on Windows

I am using this tutorial to upload Image and display it. It works well in Chrome and Firefox but it is not showing uploaded image in safari. Why?
HTML
<div id="page-wrapper">
<h1>Image File Reader</h1>
<div>
Select an image file:
<input type="file" id="fileInput">
</div>
<div id="fileDisplayArea"></div>
Javascript
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerHTML = "";
var img = new Image();
img.src = reader.result;
fileDisplayArea.appendChild(img);
}
reader.readAsDataURL(file);
} else {
fileDisplayArea.innerHTML = "File not supported!"
}
});
}
Open web development tools (Firebug for Firefox or CTRL+SHIFT+J in Chrome), select the image element with the element inspector and have a look at the URL that it is loading from and determine how it is different from the URL it should be loading from.
Since you're using Safari 5.1 on Windows, the FileReader API isn't supported and Safari on Windows will no longer be updated your best bet is to use a placeholder image from the server and call this battle a draw. Safari 5.1 market share on Windows is trivial at best and will only decrease as time goes on. Part of programming is knowing when to walk away from a fight.
if (window.FileReader)
{
//Your FileReader code here.
}
else
{
//Insert an image from the server here.
}

Categories

Resources