this is my form
<form action="#" enctype="multipart/form-data" method="post" name="..." id="formPhoto" class="fmp">
<input type="file" name="pho" id="photo" class="inph" accept="image/*">
<button type="submit" id="subFormPhoto" class="spp">press here</button>
</form>
and this is my code JS
<script type="text/javascript">
var inputPhoto= document.getElementById('photo');
inputPhoto.onchange=function(){var photo= this.value; photo.onload=function(){alert(this.width+' '+this.height);};};
</script>
my problem is that not visualize alert(this.width+' '+this.height);.
as if not load photo
this.value gives the file name as a string, so your photo.onload function isn't really looking at the photo but just some string. If you alert or console.log photo you will see what I mean.
You may wish to consider the File API, it will work with modern browsers as from HTML 5.
Here's a working example of your code:
var inputPhoto = document.getElementById('photo');
inputPhoto.onchange = function() {
var file = this.files[0];
var reader = new FileReader();
var photo = new Image();
reader.readAsDataURL(file);
reader.onload = function(_file) {
photo.src = _file.target.result;
photo.onload = function() {
alert(this.width + ' ' + this.height);
};
};
};
I have tried to create what I understood from your question
http://jsfiddle.net/qo8ovmhn/
<input type="file" name="pho" id="photo" class="inph" onchange="myFunction()">
<img id="view" src=""></img>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("photo");
var file = x.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(_file) {
var img = document.getElementById("view");
img.setAttribute("src",_file.target.result);
var height = img.offsetHeight;
var width = img.offsetWidth;
alert(width + " X " + height);
};
}
</script>
see if this is what you were looking for.
The change event of the input is called on choosing an image. The image bytes are read and put in an image tag. Then the dimensions of the image are fetched from the height and width of the image component.
You can hide the image by adding a css style of visibility:hidden or opacity:0
Do not give display:none as this will result in height and width of 0px
Finally the dimensions are shown in an alert.
Related
I have a simple form which allows you to paste an image. The image is previewed using JavaScript.
In the snippet the paste area is a textarea for testing purposes.
After the image is pasted, it’s not yet in the form’s data. Is there a way of doing this so that the image can be uploaded on submit?
var previews = document.querySelector('div#previews');
var form = document.querySelector('form#data');
form.elements['stuff'].onpaste = function (event) {
files = event.clipboardData.files;
var img = document.createElement('img');
img.width = '200';
previews.appendChild(img);
var reader = new FileReader();
reader.onload = () => {
img.src = reader.result;
};
reader.readAsDataURL(files[0])
};
textarea, input, button {
display: block;
}
<form id="data">
<textarea name="stuff"></textarea>
<input type="file" name="photo">
<button name="doit">OK</button>
</form>
<div id="previews">
</div>
I am looking for an example where the value of the <input type="file"> can be stored into a variable and then from there stored into localStorage so it is not lost when the page is refreshed, and I couldn't find the solution for what I was looking for.
function myFunction() {
//Get value of input type file
let userInput = document.getElementById("uploadImage").value;
//Store value into LocalStorage
localStorage.setItem("image", JSON.stringify(userInput))
}
// Display "image" in Local storage as src of img preview even after page refreshes
document.getElementById("imagePreview").setAttribute("src", JSON.parse(localStorage.getItem("image")))
img {
max-width: 300px;
}
<input type="file" accept="image/*" id="uploadImage">
<br>
<button onclick="myFunction()">
Submit Picture
</button>
<br>
<img id="imagePreview">
To summarize, I want to know how to save the input value into a variable, then the variable into the local storage. Finally, display the localStorage in an image tag so it is not lost when the page is refreshed. Please let me know if you have any questions as I know it might be a bit confusing. Here's a jsFiddle as shown here: https://jsfiddle.net/vedt_/zrvuwbj7/44/#&togetherjs=gbLynsQ627 feel free to edit it if you know how to do it.
You can convert the image into base64 and store it as follows:
function myFunction() {
const file = document.querySelector('#uploadImage').files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
localStorage.setItem("image", reader.result);
document.getElementById("imagePreview").setAttribute("src", localStorage.getItem("image"))
};
}
if(localStorage.getItem("image"))
document.getElementById("imagePreview").setAttribute("src", localStorage.getItem("image"))
img {
max-width: 300px;
}
<input type="file" accept="image/*" id="uploadImage"><br>
<button onclick="myFunction()">Submit Picture</button><br>
<img id="imagePreview">
First, you should use FileAPI to read the uploaded file's contents.
So you read it, then its contents to base64 and finally you can store them in the localStorage.
Also you need to create a <canvas> element to convert the image to base64.
Here is your code:
HTML:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" accept="image/*" id="uploadImage">
<br>
<button onclick="myFunction()">
Submit Picture
</button>
<br>
<img id="imagePreview">
CSS:
img {
max-width: 300px;
}
JavaScript:
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
document.getElementById("uploadImage").addEventListener("change", function() {
if (document.getElementById('uploadImage').files && document.getElementById('uploadImage').files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imagePreview').attr('src', e.target.result);
}
reader.readAsDataURL(document.getElementById('uploadImage').files[0]); // convert to base64 string
}
});
$("#imgInp").change(function() {
readURL(this);
});
function myFunction() {
bannerImage = document.getElementById('imagePreview');
imgData = getBase64Image(bannerImage);
localStorage.setItem("imgData", imgData);
}
Here is a living demo: https://codepen.io/marchmello/pen/rNOLJya
I'm trying to make an image slider. I have an array of objects like this:
var slides = [
{
img: 'images/one.jpg',
text: 'First Image'
},
{
img: 'images/two.jpg',
text: 'Second Image'
}
];
I need to have the functionality to add more images into the image slider. Hence I need to obtain the file path of the image I will be uploading and push that file path into this slides array.
I have gone through this SO answer, which effectively teaches how to upload and display an image, but my needs are different.
HTML
<div id="slide-container">
</div>
<div id="panel-container">
<form>
<label>
<span>Image Text</span>
<input type="text" class="form-control" id="image-related-text">
</label>
<label>
<span>Duration</span>
<input type="text" class="form-control" id="time-duration">
</label>
<div id="d">
<input type="file" id="image-upload">
</div>
<button id="add" disabled="true">Add to Container</button>
</form>
</div>
JS
var global_image_url = "";
// add the image and the relevant text in the slider on click of this button
$('#add').click(function(){
var imageRelatedText = $('#image-related-text').val();
var timeDuration = $('#time-duration').val();
// a new object to be pushed inside the 'slides' array
var temp_obj = {
img: 'nothing for now :|', //this should contain the image url
text: imageRelatedText
};
})
$('#image-upload').change(function(){
global_image_url = readUrl(this);
console.log(global_image_url);
});
// this function gets called when an image file is chosen
function readUrl(input){
var img = $('<img>');
var local_image_url = ""; // thought I would store the file path in this variable
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
local_image_url = JSON.stringify(e.target.result);
img.attr('src', e.target.result);
img.attr('height','100%');
img.attr('width','97%');
}
reader.readAsDataURL(input.files[0]);
}
console.log(local_image_url); // chrome developer tools freezes
return local_image_url;
}
I thought e.target.result would give the url but that's not the case. It's just another object (printed in the console once).
So how do I achieve my requirements?
Thanks!
yes e.target.result will the url, but remember FileReader reader the file content as asynchronous, if you want to output the value, you need to add some callback like :
$('#image-upload').change(function(){
readUrl(this,function(){
console.log(global_image_url);
});
});
// this function gets called when an image file is chosen
function readUrl(input,callback){
var img = $('<img>');
var local_image_url = ""; // thought I would store the file path in this variable
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
typeof callback == 'function' && callback(e.target.result);
local_image_url = JSON.stringify(e.target.result);
img.attr('src', e.target.result);
img.attr('height','100%');
img.attr('width','97%');
}
reader.readAsDataURL(input.files[0]);
}
}
My web app does not work well with long data URI that I use to display images. When the encoded data is shown within a text areas It gets unbelievably slow. Sometimes the entire page crashes when I click the download page button on my app if the data URI is somewhere in the DOM.
Is there an alternative to data URI? The user submits an image file from their computer and the data URI code is used like this to display the image <img src="dataURI"/>. This is not a server-based application so server-side languages aren't an option.
I have looked into JavaScript BLOB, although I have no idea how to work with that.
Edit, Updated
Try (v3)
html
<input id="change-image-input" type="file" accepts="image/*" />
<img src="BLOB HERE" alt="test" class="identify-selected-option-image"/>
<div></div>
js
var input = document.getElementById("change-image-input")
, div = document.querySelectorAll("div")[0]
, img = document.getElementsByClassName("identify-selected-option-image")[0];
input.addEventListener("change", function(e) {
var file = e.target.files[0];
var url = window.URL.createObjectURL(file);
img.onload = function() {
div.style.backgroundImage = "url('" + url + "')";
div.style.width = img.width + "px";
div.style.height = img.height + "px";
}
img.src = url;
});
var input = document.getElementById("change-image-input")
, div = document.querySelectorAll("div")[0]
, img = document.getElementsByClassName("identify-selected-option-image")[0];
input.addEventListener("change", function(e) {
var file = e.target.files[0];
var url = window.URL.createObjectURL(file);
img.onload = function() {
div.style.backgroundImage = "url('" + url + "')";
div.style.width = img.width + "px";
div.style.height = img.height + "px";
}
img.src = url;
});
<input id="change-image-input" type="file" accepts="image/*" />
<img src="BLOB HERE" alt="test" class="identify-selected-option-image"/>
<div></div>
You can create an Image from File or Blob using URL.createObjectURL, which can then be set as img src, painted on canvas, or set as target of download link.
Example HTML:
<!DOCTYPE html>
<input type="file" onchange="update()" />
<a download><img alt="Please select a photo" /></a>
And JavaScript:
function update() {
var a = document.querySelector( 'a' );
var f = document.querySelector( 'input' ).files;
var url = window.URL || window.webkitURL;
if ( ! f || ! f.length ) return;
a.href = document.querySelector( 'img' ).src = url.createObjectURL( f[0] );
}
The image displays on IE 11, Chrome 39, Firefox 33.
The download link works in Chrome and Firefox, but is not supported in IE <=11.
IE users will have to manually right click to save image.
I'm trying to access a camera and a photo album on a mobile device and get the chosen image. I did that with the code below. My problem is, it generates image data, and I have to transfer that to another page, but because of the size of the generated string, I can't use URL parameters. It shows me the error: [404] Request-URI Too long. How can I pass the information to the other page?
Here is the code: http://jsfiddle.net/8u426/
The JS:
<script>
oFReader = new FileReader();
oFReader.onload = function (oFREvent) {
document.getElementById("fotoImg").src = oFREvent.target.result;
document.getElementById("fotoImg").style.visibility = "visible";
var screenHeight = screen.availHeight;
screenHeight = screenHeight - 220;
document.getElementById("fotoImg").style.height = screenHeight;
document.getElementById("stringImg").innerText = "Data Image: " + oFREvent.target.result;
};
$(function() {
$("input:file").change(function (){
var input = document.querySelector('input[type=file]');
var oFile = input.files[0];
oFReader.readAsDataURL(oFile);
});
});
</script>
Update:
The problem is: if I try to open a new page passing the Data Image string as a parameter in the URL (with "?"). The new page will show the 404 error that I mentioned, because the string is too long.
Try changing your form to
<form id="form1" method="POST" action="[Page2 URL]">
<input id="filePic" type="file" name="image" accept="image/*" capture />
</form>
where [Page2 URL] is the URL for page to receive the image uploaded.
And JavaScript to
oFReader = new FileReader();
oFReader.onload = function (oFREvent) {
var screenHeight = screen.availHeight;
screenHeight = screenHeight - 220;
var img = $('#fotoImg');
img.attr('src', oFREvent.target.result);
img.css( { height : screenHeight, visibility: 'visible' });
$("#stringImg").text( "Data Image: " + oFREvent.target.result);
$('#form1').submit();
};
$(function() {
$("input:file").change(function (){
var oFile = this.files[0];
oFReader.readAsDataURL(oFile);
});
});
I couldn't make work with php (considering that I didn't want to work with php) and html forms (methods get and post)... So I used the jQuery library called "jQuery Storage".
It was easy, on the page that I select the image you shoud use:
$.sessionStorage([key],[value]);
So, was like that:
$.sessionStorage('chosenImg', document.getElementById("photoImg").src);
And in the new page, to get the value, just add in the code:
$.sessionStorage('chosenImg');
Of course, I had to download de .js library from the website and add the line below on both html pages:
<script src="jquery.storage.js"></script>
The only inconvenient it is a little heavy for mobile, but was the only way I found...
That is it! Thanks everyone!
dataimage base64 data image