JS - File Reader API get image file size and dimensions - javascript

Hi i'm using the following code to get the upload image using File Reader API:
<script type="text/javascript">
var loadImageFile = (function () {
if (window.FileReader) {
var oPreviewImg = null, oFReader = new window.FileReader(),
rFilter = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i;
oFReader.onload = function (oFREvent) {
/*get image*/
var _img = oFREvent.target.result;
console.log(oFREvent.target);
/*add img to hidden input text*/
localStorage.photo = _img;
oPreviewImg.src = oFREvent.target.result;
};
return function () {
var aFiles = document.getElementById("imageInput").files;
if (aFiles.length === 0) { return; }
if (!rFilter.test(aFiles[0].type)) {
notify("You must select a valid image file!",3400,false); return;
}
oFReader.readAsDataURL(aFiles[0]);
}
}
})();
</script>
<form name="uploadForm">
<p><input id="imageInput" type="file" name="myPhoto" onchange="loadImageFile();" /><br />
<input type="submit" value="Send" /></p>
<input type="hidden" id="photo_1_hidden" name="photo_1"/>
</form>
it works great and it returns the base64 data of the image.
now i would like to get also the image file size and the image width and height.
Is it possible?
I tryed to log in console the file but i can't find what i'm searching for.
Any help appriciated thanks so much!

Something like this?
var oPreviewImg = new Image();
oPreviewImg.onload = function(){
console.log(this.size);
alert("'" + this.name + "' is " + this.width + " by " + this.height + " pixels in size.");
return true;
};
oPreviewImg.onerror = function(){
alert("'" + this.name + "' failed to load.");
return true;
}
oPreviewImg.src = "//placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150";
var xhr = new XMLHttpRequest();
xhr.open('HEAD', oPreviewImg.src, true);
xhr.onreadystatechange = function() {
console.log('this', this);
if ( xhr.readyState == 4 ) {
if ( xhr.status == 200 ) {
alert('Size in bytes: ' + xhr.getResponseHeader('Content-Length'));
} else {
alert('ERROR');
}
}
};
xhr.send(null);
Live version
Update Live version replaced with Fiddle, however, due to cross site scripting concerns, the size is no longer being retrieved effectively.

const reader = new FileReader()
reader.onload = (theFile) => {
const image = new Image()
image.src = theFile.target.result
image.onload = () => {
console.log('image width ===== ' + image.width + 'Image height
===== ' + image.height)
}
}
reader.readAsDataURL(item)

I don't believe that JS is going to be capable of getting that data without first rendering the image to the viewport. That is to say, I am unfamiliar of any method that would do what you ask in the JavaScript, or JQuery libraries. Your best bet for getting data like that is going to be rendering the image to the page in a preview capacity or using a more powerful language like PHP and using an Ajax request to get the data you're looking for.

Related

SAPUI5 How to decode qrcode from qrcode image

How to scan QRCode data from QRCode image(jpg/png) that is available in local System. From UI5 library im able to find BarcodeScanner. Using below code im able to open Camera from my device and able to scan the barcodes..
sap.ndc.BarcodeScanner.scan(
function(mResult) {
alert("We got a bar code\n" +
"Result: " + mResult.text + "\n" +
"Format: " + mResult.format + "\n" +
"Cancelled: " + mResult.cancelled);
},
function(Error) {
alert("Scanning failed: " + Error);
},
);
But how to decode QRCode image data? can someone please help me?
Thankyou in advance
You could use this lib for reading qr codes: https://github.com/LazarSoft/jsqrcode
In this function the file is read and the decoded result is outputted in a div container
function readFile(oFile) {
var input = oFile.target;
var reader = new FileReader();
reader.onload = function() {
var dataURL = reader.result;
decodeImageFromBase64(dataURL, function(decodedInformation) {
document.getElementById("output").innerHTML = decodedInformation;
})
};
reader.readAsDataURL(input.files[0]);
}
In this fuction the decoding magic is happen
function decodeImageFromBase64(data, callback) {
qrcode.callback = callback;
qrcode.decode(data)
}

AngularJS: Is there any way to get size of file?

I'm implementing a check in which I dont want to upload the image which has size greater than 4MB. I'm using file reader and new image(). I've the image size and width. But how can I get the filesize.
function previewImage(element) {
var reader = new FileReader();
reader.onload = function (event) {
seAddArtist.imageSource = event.target.result;
$scope.$apply();
};
// when the file is read it triggers the onload event above.
reader.readAsDataURL(element.files[0]);
}
var img = new Image();
img.onload = function () {
alert(this.width + 'x' + this.height);
}
I am implementing these two combine but how can i check the size of image?
FileReader (FileReader API) itself does not provide the size of an file. You need to use file (file API) instead:
function previewImage(element) {
var reader = new FileReader();
reader.onload = function(event) {
seAddArtist.imageSource = event.target.result;
$scope.$apply();
};
// when the file is read it triggers the onload event above.
reader.readAsDataURL(element.files[0]);
//log / access file size in bytes
console.log(element.files[0].size + ' Bytes');
//log / access file size in Mb
console.log(element.files[0].size/1024/1024 + ' MB');
if (element.files[0].size/1024/1024 > 4) {
console.log('file is bigger than 4MB);
}
}
That might be what you want:
var size = files[0].size;
You can check the file size before submitting:
<!doctype HTML>
<html>
<head>
<script>
function checkFileSize() {
var size = document.getElementById("fileSelector").files[0].size;
alert("file size: " + size);
}
</script>
</head>
<body>
<input id="fileSelector" type="file" onchange="checkFileSize()"/>
<input type="submit" />
</body>
</html>
This is working code to get file size. you will get file size in KB.
<input id="file" type="file">
<img id="filerendered" src="">
and in script tag
document.getElementById('file').onchange = function (event) {
var targetn = event.target || window.event.srcElement,
files = targetn.files;
// FileReader here
if (FileReader && files && files.length) {
var thisReader = new FileReader();
alert("your file size "+ (files[0].size)/1024 + "kb")
thisReader.onload = function () {
document.getElementById("filerendered").src = thisReader.result;
}
thisReader.readAsDataURL(files[0]);
}
// for Not supported case
else {
// not supported
}
}

file upload not working after updating jquery

I've searched everything but my error stays.
Following scripts is my code:
var client = null;
function fileChange()
{
var fileList = document.getElementById("fileA").files;
var file = fileList[0];
if(!file)
return;
document.getElementById("progress").value = 0;
document.getElementById("prozent").innerHTML = "0%";
}
function uploadFile()
{
var file = document.getElementById("fileA").files[0];
var formData = new FormData();
client = new XMLHttpRequest();
var prog = document.getElementById("progress");
if(!file)
return;
prog.value = 0;
prog.max = 100;
formData.append("datei", file);
client.onerror = function(e) {
alert("onError");
};
client.onload = function(e) {
document.getElementById("prozent").innerHTML = "100%";
prog.value = prog.max;
};
client.upload.onprogress = function(e) {
var p = Math.round(100 / e.total * e.loaded);
document.getElementById("progress").value = p;
document.getElementById("prozent").innerHTML = p + "%";
};
client.onabort = function(e) {
alert("Upload abgebrochen");
};
client.open("POST", "upload.php");
client.send(formData);
}
And my upload.php:
<?php
if (isset($_FILES['datei']))
{
//console.log("upload.php!");
//move_uploaded_file($_FILES['datei']['tmp_name'], 'upload/'.basename($_FILES['datei']['name']));
move_uploaded_file($_FILES['datei']['tmp_name'], 'upload/hextoflash.hex');
}
else
{
echo "error in $_files";
}
?>
and html:
<form name="uploadform" method="post" enctype="multipart/form-data" action="">
<br> <input name="uploaddatei" type="file" id="fileA" onchange="fileChange();" /> </br>
<input name="uploadbutton" value="Hochladen!" style="width: 108px" type="button" onclick="uploadFile();" />
</form>
The point is, i already tried to edit php.ini.
I checked max_size and so on, its already in the right dimension
File was working with an old jquery.js, i updated to jquery2.2.0 because of datatables plugin, so i need that, and since then it seems to not work anymore
the rights of the upload folder are 777
So i don't get where the problem is, and if its within jquery, im not able to fix that. is there a method to fix this problem?
I found the solution.
It was so easy i would never think of it.
The server drive was simply 100% full.
Deleted some junk and voilá it's running.

Upload image using javascript

I'm trying to get image as Object of javascript on the client side to send it using jQuery
<html>
<body>
<script language="JavaScript">
function checkSize()
{
im = new Image();
im.src = document.Upload.submitfile.value;
if(!im.src)
im.src = document.getElementById('submitfile').value;
alert(im.src);
alert(im.width);
alert(im.height);
alert(im.fileSize);
}
</script>
<form name="Upload" action="#" enctype="multipart/form-data" method="post">
<p>Filename: <input type="file" name="submitfile" id="submitfile" />
<input type="button" value="Send" onClick="checkSize();" />
</form>
</body>
</html>
But in this code only alert(im.src) is displaying src of file but alert(im.width),alert(im.height),alert(im.filesize) are not working properly and alerting 0, 0, undefined respectively. Kindly tell me how I can access image object using javascript?
The reason that im.fileSize is only working in IE is because ".fileSize" is only an IE property. Since you have code that works in IE, I would do a check for the browser and render your current code for IE and try something like this for other browsers.
var imgFile = document.getElementById('submitfile');
if (imgFile.files && imgFile.files[0]) {
var width;
var height;
var fileSize;
var reader = new FileReader();
reader.onload = function(event) {
var dataUri = event.target.result,
img = document.createElement("img");
img.src = dataUri;
width = img.width;
height = img.height;
fileSize = imgFile.files[0].size;
alert(width);
alert(height);
alert(fileSize);
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsDataURL(imgFile.files[0]);
}
I haven't tested this code but it should work as long as I don't have some typo. For a better understanding of what I am doing here check out this link.
This is what I use and it works great for me. I save the image as a blob in mysql. When clicked, the file upload dialog appears, that is why i set the file input visibility to hidden and set its type to upload image files. Once the image is selected, it replaces the existing one, then I use the jquery post method to update the image in the database.
<div>
<div><img id="logo" class="img-polaroid" alt="Logo" src="' . $row['logo'] . '" title="Click to change the logo" width="128">
<input style="visibility:hidden;" id="logoupload" type="file" accept="image/* ">
</div>
$('img#logo').click(function(){
$('#logoupload').trigger('click');
$('#logoupload').change(function(e){
var reader = new FileReader(),
files = e.dataTransfer ? e.dataTransfer.files : e.target.files,
i = 0;
reader.onload = onFileLoad;
while (files[i]) reader.readAsDataURL(files[i++]);
});
function onFileLoad(e) {
var data = e.target.result;
$('img#logo').attr("src",data);
//Upload the image to the database
//Save data on keydown
$.post('test.php',{data:$('img#logo').attr("src")},function(){
});
}
});
$('#imagess').change(function(){
var total_images=$('#total_images').val();
var candidateimage=document.getElementById('imagess').value;
formdata = false;
var demo=document.getElementById("imagess").files;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = demo.length, img, reader, file;
for ( ; i < len; i++ ) {
file = demo[i];
if (file.type.match(/image.*/)) {
if (formdata) {
formdata.append("images", file);
}
}
}
$('#preview').html('Uploading...');
var url=SITEURL+"users/image_upload/"+total_images;
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
$('#preview').html('');
if (res == "maxlimit") {
alert("You can't upload more than 4 images");
}
else if (res == "error") {
alert("Image can't upload please try again.")
}
else {
$('#user_images').append(res);
}
}
});
});

How do I change the list of uploaded files?

I am attempting to use XMLHttpRequest to upload files to the server. Here are the steps I would like the code to do:
List the file in a file list ul
Upload the file(s) while displaying a progress bar
When the file is completely uploaded, change the list item for that file to a link without the progress bar. This is where I am having a problem.
Here is the HTML code I am working with:
<h1>Upload Files</h1>
<input type='file' name='doc_upload_field[][]' multiple='multiple' id='doc_upload_field' />
<ul id='filelist'></ul>
Here is the javascript code I am working with:
function transferFailed(evt) {
alert("An error occurred while transferring the file.");
}
function transferCanceled(evt) {
alert("The transfer has been canceled by the user.");
}
var filelist = $('#filelist');//define where the list of files will go
var url = "/";
function handleFileSelect_inputfield(evt) {
var files = evt.target.files; // FileList object
// run through each file individually.
for (var i = 0, f; f = files[i]; i++) {
var li = $("<li><strong>" + f.name + "</strong> (" + f.type +") - " + f.size + " bytes <div class='progress_bar'><div class='percent'> </div></div></li>");
filelist.append(li);//put the file in the filelist
var formData = new FormData();
formData.append(f.name, f);
//upload through xmlhttprequest
var xhr = new XMLHttpRequest();
xhr.upload.li = li;
xhr.upload.addEventListener("progress", function(e) {
if (e.lengthComputable) {
var percentLoaded = Math.round((e.loaded / e.total) * 100);
// Increase the progress bar length.
if (percentLoaded < 100) {
this.li.find(".progress_bar").addClass('loading');
this.li.find(".percent").width(percentLoaded + '%');
}
}
}, false);
xhr.upload.addEventListener("load", function(e) {
//uploading is complete
}, false);
xhr.upload.addEventListener("error", transferFailed, false);
xhr.upload.addEventListener("abort", transferCanceled, false);
xhr.open('POST', url, true);
xhr.responseType = 'text';
xhr.onload = function(e) {
if (this.readyState==4){
if (this.status == 200) {
//console.log(this.response);
console.log("finished=" + li);//returns as an object
//console.log("filename=" + f.name);//error: cannot read property 'name' of undefined
//change the list item. Not working...
this.li.find("li").html("<a href='#'>" + f.name + "</a>");
}
}
};
xhr.send(formData); // multipart/form-data
}
}
document.getElementById('doc_upload_field').addEventListener('change', handleFileSelect_inputfield, false);
Everything seems to be working, but when I want to change the list item, li, it is not recognizing it. I am able to change the progress bar length by calling:
this.li.find(".progress_bar").addClass('loading');
this.li.find(".percent").width(percentLoaded + '%');
But when I want to change the list item:
this.li.find("li").html("<a href='#'>" + f.name + "</a>");
It does not work.
Does anyone know why it would find it when changing the progress bar, but not find it after it is uploaded?
The expression
this.li.find("li")
looks for an <li> element inside the other <li> element. There isn't one, so nothing happens.
I think that just
this.li.html("<a href='#'>" + f.name + "</a>");
should be what you want. Or you could just do this:
this.li = $("<li><a href='#'>" + f.name + "</a></li>");
edit oops no that won't work because you've stuck it in the DOM already. But the first one should work.
edit — you've also got a closure-related problem (or scope-related; whatever). What you can do is something like what you've already done for the "li" value. Add another property for it to "xhr.upload":
xhr.upload.updated_li = "<a href='#'>" + f.name + "</a>";
Do that right where you set "xhr.updated.li". Then, in the event handler, you can do:
this.li.html(this.updated_li);

Categories

Resources