Dragging local image in webpage crashes Chrome - javascript

I'm working on a page where users can view/upload local files. Once the file has been selected, I'm displaying the image in the page. I've come across an issue that dragging such an image crashes my browser window (Chrome).
Here's a jsfiddle.
Simple html:
<input type='file'>
<img>
Javascript (jQuery):
$('input').change(function(){
var file = $('input').get(0).files;
var fileReader=new FileReader();
fileReader.onload = function(e){
$('img').attr('src',e.target.result);
};
fileReader.readAsDataURL(file[0]);
});
Poking around a bit more, it seems this is only a problem with large image files (such as uncompressed photos from an iPhone). This isn't necessarily a deal-breaker for the page but it is certainly annoying to accidentally drag an image and instantly crash the page.
Is there any good way to fix this?

I solved using Blob :
if (file !== undefined && window.FileReader !== undefined) {
var reader = new FileReader();
var self = this;
reader.onload = function(e) {
if (window.Blob) {
var blob = new Blob([e.target.result]);
window.URL = window.URL || window.webkitURL;
var blobURL = window.URL.createObjectURL(blob);
self.setSrc({"tempUrl" : blobURL}); //using backbone this refers to a model
}
};
reader.readAsArrayBuffer(file);
} else {
if (!file)
console.error("No file prevented");
if (!window.FileReader)
console.error("Your browser is not supported");
}
As I could see, readAsDataURL kills the memory.

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"

Changing Src of an Embed Swf Player

So I'm working on a little project which has a little over 50 swf movies, and I wanted to be able to watch them like a normal human being (play, pause, rewind and all those good stuff).
Anywho, I've made all that happen..
The only thing I can't seem to get is changing the embed flash player dynamically, i.e the user chooses the .swf file to be shown instead of the path being hard-coded.
This is my code so far:
function changePlayerSrc()
{
var player = document.getElementById("flash_player_obj"); //selects the flash player object
var file = document.querySelector('input[type=file]').files[0]; //get the user's file
var reader = new FileReader();
reader.onloadend = function()
{
var clone = player.cloneNode(true); //cloned player
var res = reader.result; //user's file as blob
clone.childNodes[1].setAttribute('src', res); //change src
player.parentNode.replaceChild(clone, player);
}
reader.readAsDataURL(file);
}
<object id = "flash_player_obj">
<embed = "flash_player_embed"
name = "flash_player"
src = "H:\test.swf"
width = "100%"
height = "500"
play = "false"
loop = "false"
quality = "high"
scale = "showall"
/>
</object>
<input type="file" onchange="changePlayerSrc()" />
The above code just gives me a blank flash player with nothing playing.
I've also tried using reader.readAsArrayBuffer(file);
var res = reader.result;
var blob = new Blob([res], {type: "application/x-shockwave-flash"});
var url = URL.createObjectURL(blob);
And using the url as src for the embed, this just opens the save file dialog for some reason..
Also note that I'm not using any server side code, because there isn't any server to work with.
This script is running solely on a single .html file.

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.
}

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

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/

how to validate image size and dimensions before saving image in database

I am using ASP.NET C# 4.0, my web form consist of input type file to upload images.
i need to validate the image on client side, before saving it to my SQL database
since i am using input type= file to upload images, i do not want to post back the page for validating the image size, dimensions.
Needs your assistance
Thanks
you can do something like this...
You can do this on browsers that support the new File API from the W3C, using the readAsDataURL function on the FileReader interface and assigning the data URL to the src of an img (after which you can read the height and width of the image). Currently Firefox 3.6 supports the File API, and I think Chrome and Safari either already do or are about to.
So your logic during the transitional phase would be something like this:
Detect whether the browser supports the File API (which is easy: if (typeof window.FileReader === 'function')).
If it does, great, read the data locally and insert it in an image to find the dimensions.
If not, upload the file to the server (probably submitting the form from an iframe to avoid leaving the page), and then poll the server asking how big the image is (or just asking for the uploaded image, if you prefer).
Edit I've been meaning to work up an example of the File API for some time; here's one:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show Image Dimensions Locally</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript'>
function loadImage() {
var input, file, fr, img;
if (typeof window.FileReader !== 'function') {
write("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('imgfile');
if (!input) {
write("Um, couldn't find the imgfile element.");
}
else if (!input.files) {
write("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
write("Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = createImage;
fr.readAsDataURL(file);
}
function createImage() {
img = document.createElement('img');
img.onload = imageLoaded;
img.style.display = 'none'; // If you don't want it showing
img.src = fr.result;
document.body.appendChild(img);
}
function imageLoaded() {
write(img.width + "x" + img.height);
// This next bit removes the image, which is obviously optional -- perhaps you want
// to do something with it!
img.parentNode.removeChild(img);
img = undefined;
}
function write(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
}
</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='imgfile'>
<input type='button' id='btnLoad' value='Load' onclick='loadImage();'>
</form>
</body>
</html>
Works great on Firefox 3.6. I avoided using any library there, so apologies for the attribute (DOM0) style event handlers and such.
function getImgSize(imgSrc) {
var newImg = new Image();
newImg.onload = function() {
var height = newImg.height;
var width = newImg.width;
alert ('The image size is '+width+'*'+height);
}
newImg.src = imgSrc; // this must be done AFTER setting onload
}

Categories

Resources