How to get image width and height using JavaScript before upload? - javascript

How to get image width and height using Javascript before upload? I tried to test my code, but it does not work. How can I achieve this?
https://jsfiddle.net/r78qkjba/1/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input name="offer_image_1" onchange="check_thumbnail_image_format_fn()" type="file" id="offer_image_1" />
<script>
function check_thumbnail_image_format_fn() {
var offer_image_1_data = document.getElementById("offer_image_1");
var offer_image_1_data_file = offer_image_1_data.files[0];
var offer_image_1_data_file_width = offer_image_1_data_file.width;
var offer_image_1_data_file_height = offer_image_1_data_file.height;
alert(offer_image_1_data_file_width);
alert(offer_image_1_data_file_height);
};
</script>

HTML5 and the File API
Here's the uncommented working code snippet example:
window.URL = window.URL || window.webkitURL;
var elBrowse = document.getElementById("browse"),
elPreview = document.getElementById("preview"),
useBlob = false && window.URL; // `true` to use Blob instead of Data-URL
function readImage (file) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.addEventListener("load", function () {
var imageInfo = file.name +' '+
image.width +'×'+
image.height +' '+
file.type +' '+
Math.round(file.size/1024) +'KB';
elPreview.appendChild( this );
elPreview.insertAdjacentHTML("beforeend", imageInfo +'<br>');
});
image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
if (useBlob) {
window.URL.revokeObjectURL(file); // Free memory
}
});
reader.readAsDataURL(file);
}
elBrowse.addEventListener("change", function() {
var files = this.files;
var errors = "";
if (!files) {
errors += "File upload not supported by your browser.";
}
if (files && files[0]) {
for(var i=0; i<files.length; i++) {
var file = files[i];
if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
readImage( file );
} else {
errors += file.name +" Unsupported Image extension\n";
}
}
}
if (errors) {
alert(errors);
}
});
#preview img{height:100px;}
<input id="browse" type="file" multiple />
<div id="preview"></div>
Using an input and a div for the images preview area
<input id="browse" type="file" multiple>
<div id="preview"></div>
let's also use a CSS to keep the resulting images a reasonable height:
#preview img{ height:100px; }
JavaScript:
window.URL = window.URL || window.webkitURL;
var elBrowse = document.getElementById("browse"),
elPreview = document.getElementById("preview"),
useBlob = false && window.URL; // `true` to use Blob instead of Data-URL
// 2.
function readImage (file) {
// 2.1
// Create a new FileReader instance
// https://developer.mozilla.org/en/docs/Web/API/FileReader
var reader = new FileReader();
// 2.3
// Once a file is successfully readed:
reader.addEventListener("load", function () {
// At this point `reader.result` contains already the Base64 Data-URL
// and we've could immediately show an image using
// `elPreview.insertAdjacentHTML("beforeend", "<img src='"+ reader.result +"'>");`
// But we want to get that image's width and height px values!
// Since the File Object does not hold the size of an image
// we need to create a new image and assign it's src, so when
// the image is loaded we can calculate it's width and height:
var image = new Image();
image.addEventListener("load", function () {
// Concatenate our HTML image info
var imageInfo = file.name +' '+ // get the value of `name` from the `file` Obj
image.width +'×'+ // But get the width from our `image`
image.height +' '+
file.type +' '+
Math.round(file.size/1024) +'KB';
// Finally append our created image and the HTML info string to our `#preview`
elPreview.appendChild( this );
elPreview.insertAdjacentHTML("beforeend", imageInfo +'<br>');
});
image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
// If we set the variable `useBlob` to true:
// (Data-URLs can end up being really large
// `src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAA...........etc`
// Blobs are usually faster and the image src will hold a shorter blob name
// src="blob:http%3A//example.com/2a303acf-c34c-4d0a-85d4-2136eef7d723"
if (useBlob) {
// Free some memory for optimal performance
window.URL.revokeObjectURL(file);
}
});
// 2.2
// https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
reader.readAsDataURL(file);
}
// 1.
// Once the user selects all the files to upload
// that will trigger a `change` event on the `#browse` input
elBrowse.addEventListener("change", function() {
// Let's store the FileList Array into a variable:
// https://developer.mozilla.org/en-US/docs/Web/API/FileList
var files = this.files;
// Let's create an empty `errors` String to collect eventual errors into:
var errors = "";
if (!files) {
errors += "File upload not supported by your browser.";
}
// Check for `files` (FileList) support and if contains at least one file:
if (files && files[0]) {
// Iterate over every File object in the FileList array
for(var i=0; i<files.length; i++) {
// Let's refer to the current File as a `file` variable
// https://developer.mozilla.org/en-US/docs/Web/API/File
var file = files[i];
// Test the `file.name` for a valid image extension:
// (pipe `|` delimit more image extensions)
// The regex can also be expressed like: /\.(png|jpe?g|gif)$/i
if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
// SUCCESS! It's an image!
// Send our image `file` to our `readImage` function!
readImage( file );
} else {
errors += file.name +" Unsupported Image extension\n";
}
}
}
// Notify the user for any errors (i.e: try uploading a .txt file)
if (errors) {
alert(errors);
}
});

Hope below code will help you.
var _URL = window.URL || window.webkitURL;
$("#offer_image_1").change(function (e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
alert(this.width + " " + this.height);
};
img.src = _URL.createObjectURL(file);
}
});
You don't need to add onchange event at the input node.
This code is taken from
Check image width and height before upload with Javascript

Related

ReferenceError: PDFJS is not defined Asp.net

I'm trying to display a pdf using canvas and PDF.JS Stable v.2.2.228 but when I execute my webform it shows this error in the console: ReferenceError: PDFJS is not defined.
I read something about the global PDFJS object being removed but I can't find the correct syntax [Kinda new in JS]. Any suggestion is very appreciated
I was following this example in case is needed : https://usefulangle.com/post/20/pdfjs-tutorial-1-preview-pdf-during-upload-wih-next-prev-buttons
Js code:
function showPDF(pdf_url) {
PDFJS.getDocument({ url: pdf_url }).then(function (pdf_doc) {
__PDF_DOC = pdf_doc;
__TOTAL_PAGES = __PDF_DOC.numPages;
// Show the first page
showPage(1);
}).catch(function (error) {
// If error re-show the upload button
alert(error.message);
});;
}
function showPage(page_no) {
__PAGE_RENDERING_IN_PROGRESS = 1;
__CURRENT_PAGE = page_no;
__PDF_DOC.getPage(page_no).then(function (page) {
// As the canvas is of a fixed width we need to set the scale of the viewport accordingly
var scale_required = __CANVAS.width / page.getViewport(1).width;
// Get viewport of the page at required scale
var viewport = page.getViewport(scale_required);
// Set canvas height
__CANVAS.height = viewport.height;
var renderContext = {
canvasContext: __CANVAS_CTX,
viewport: viewport
};
page.render(renderContext).then(function () {
__PAGE_RENDERING_IN_PROGRESS = 0;
// Show the canvas and hide the page loader
$("#pdf-canvas").show();
});
});
}
function ValidateFileUpload() {
var fuData = document.getElementById('FileUpload1');
var FileUploadPath = fuData.value;
//To check if user upload any file
if (FileUploadPath == '') {
alert("Por favor subir un archivo");
} else {
var Extension = FileUploadPath.substring(
FileUploadPath.lastIndexOf('.') + 1).toLowerCase();
//The file uploaded is an image
if (Extension == "png" || Extension == "jpeg" || Extension == "jpg" || Extension == "gif" || Extension == "jfif") {
// To Display
if (fuData.files && fuData.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#ImgPreview').attr('src', e.target.result);
//document.getElementById('ImgPreview').files[0].name;
var nombre= document.getElementById('ImgPreview').files[0].name;
document.querySelector('#LblFileupload').innerText = nombre;
}
reader.readAsDataURL(fuData.files[0]);
}
}
else if (Extension == "pdf") {
var __PDF_DOC,
__CURRENT_PAGE,
__TOTAL_PAGES,
__PAGE_RENDERING_IN_PROGRESS = 0,
__CANVAS = $('#pdf-canvas').get(0),
__CANVAS_CTX = __CANVAS.getContext('2d');
showPDF(URL.createObjectURL($("#FileUpload1").get(0).files[0]));
}
//The file upload is NOT an image
else {
alert("Solo se aceptan archivos en formato .JPG - .PNG - .JPEG - .GIF - .JFIF");
}
}
}
HTML :
<asp:FileUpload ID="FileUpload1" runat="server" accept="image/*" onchange="return ValidateFileUpload()" Visible="true" />
<asp:Image ID="ImgPreview" runat="server" Height="600px" Width="500px" />
<canvas id="pdf-canvas" width="400"> </canvas>
You should change PDFJS to pdfjsLib. Also you should try adding the lines var __CANVAS = $('#pdf-canvas').get(0); and var __CANVAS_CTX = __CANVAS.getContext('2d'); under __CURRENT_PAGE = page_no; in that function because you're not initializing those variables before you try to call and use them. Also you need to add var in front of the other two items you're using in that function at the top.
So it should look like:
pdfjsLib.getDocument(URL.createObjectURL($("#FileUpload1").get(0).files[0])).then(doc => {
console.log("This file has " + doc._pdfInfo.numPages + "pages");
doc.getPage(1).then(page => {
var myCanvas = document.getElementById('pdf-canvas');
var context = myCanvas.getContext('2d');
var viewport = page.getViewport(1);
myCanvas.width = viewport.width;
myCanvas.height = viewport.height;
page.render({
canvasContext: context,
viewport : viewport
}
);
});
});

Jquery validating - comparing the content of jquery variables

I am writing a script which allows users to up load image files. Each user has an account to login and when they do so a data table is read and returns a list of screens associated to their account.
The user selects a screen and a jQuery script returns the screen resolution.
var w;
var h;
$(document).ready(function()
{
$('#board').change(function(){
$.get('check_override_image.php', { RecordID: form2.board.value },
function(result) {
result = JSON.parse(result);
w = result["imagesizes"][0]["DisplayWidth"];
h = result["imagesizes"][0]["DisplayHeight"];
$('#size').html("Display width: " + result["imagesizes"][0]["DisplayWidth"]
+ ",<br> Display height: " + result["imagesizes"][0]["DisplayHeight"]).show();
if (result["imagesizes"][0]["DisplayType"] == 'P' ) {
$("#portrait").show();
$("#landscape").hide();
$("#SelectView").show();
$("#SelectViewText").show();
} else {
$("#landscape").show();
$("#portrait").hide();
$("#SelectView").show();
$("#SelectViewText").show();
}
});
});
});
The user clicks on a "Browse" link to select an image from their local drive and another jQuery script returns the image filename and the image dimensions.
$(document).ready(function(){
//LOCAL IMAGE
var _URL = window.URL || window.webkitURL;
$("#image_field").change(function (e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
if ( this.width != w || this.height != y) {
alert(this.width + " " + this.height);
};
};
img.src = _URL.createObjectURL(file);
}
});
});
My question: is there a way I can use the result["imagesizes"][0]["DisplayWidth"]and result["imagesizes"][0]["DisplayHeight"] along with "this.width" and "this.height" to make sure the the selected image dimensions are the same as the selected screen resolution?
I worked out how this is done and updated my question code to reflect

Strip EXIF data from image

How can I strip the EXIF data from an uploaded image through javascript? I am currently able to access the EXIF data using this exif-js plugin, like this:
EXIF.getData(oimg, function() {
var orientation = EXIF.getTag(this, "Orientation");
});
However, I have not found any way to actually remove the Exif data, only to retrieve it.
More specifically, I am trying to do this to get rid of the orientation Exif data which rotates my image on certain browsers.
look up the file format and exif format
read the file into arraybuffer
find the required data and remove it
create a blob from the remaining data
upload it with ajax
Here is a little demo of it, select an image with orientation data to see how it looks with and with out it(modern browsers only).
http://jsfiddle.net/mowglisanu/frhwm2xe/3/
var input = document.querySelector('#erd');
input.addEventListener('change', load);
function load(){
var fr = new FileReader();
fr.onload = process;
fr.readAsArrayBuffer(this.files[0]);
document.querySelector('#orig').src = URL.createObjectURL(this.files[0]);
}
function process(){
var dv = new DataView(this.result);
var offset = 0, recess = 0;
var pieces = [];
var i = 0;
if (dv.getUint16(offset) == 0xffd8){
offset += 2;
var app1 = dv.getUint16(offset);
offset += 2;
while (offset < dv.byteLength){
//console.log(offset, '0x'+app1.toString(16), recess);
if (app1 == 0xffe1){
pieces[i] = {recess:recess,offset:offset-2};
recess = offset + dv.getUint16(offset);
i++;
}
else if (app1 == 0xffda){
break;
}
offset += dv.getUint16(offset);
var app1 = dv.getUint16(offset);
offset += 2;
}
if (pieces.length > 0){
var newPieces = [];
pieces.forEach(function(v){
newPieces.push(this.result.slice(v.recess, v.offset));
}, this);
newPieces.push(this.result.slice(recess));
var br = new Blob(newPieces, {type: 'image/jpeg'});
document.querySelector('#mod').src = URL.createObjectURL(br);
}
}
}
img{
max-width:200px;
}
<input id="erd" type="file"/><br>
<img id="orig" title="Original">
<img id="mod" title="Modified">

HTML5 Drag and Drop only images

What i'm trying to do is : if all the dragged files was images drop them, but if there was other file exstensions don't drop them, but drop the images only.
Here's my try :
HTML :
<div id="dropzone"></div>
Javascript :
var dropzone = document.getElementById("dropzone");
dropzone.ondrop = function (e) {
e.preventDefault();
e.stopPropagation();
var files = e.dataTransfer.files;
for(x = 0; x < files.length; x = x + 1){
if(files[x].type.split("/")[0] == 'image') {
console.log(files[x].name + "is image");
}else {
console.log(files[x].name + "is not image");
}
}
}
i need to loop through the files that i dragged and if the file was image do something otherwise do something else, for example
file.jpeg is image
file.txt is not image
But using my code if i dragged other file extension with the image it's not dropping the image, it's skipping both files.
The point is : Dropping only images.
You could use the FileReader and test the file type for an image like this:
// don't try to process non-images
var imageType = /image.*/;
if (file.type.match(imageType)) {
// it's an image, process it
}
Here's example code and a Demo:
// dropzone event handlers
var dropzone;
dropzone = document.getElementById("dropzone");
dropzone.addEventListener("dragenter", dragenter, false);
dropzone.addEventListener("dragover", dragover, false);
dropzone.addEventListener("drop", drop, false);
//
function dragenter(e) {
e.stopPropagation();
e.preventDefault();
}
//
function dragover(e) {
e.stopPropagation();
e.preventDefault();
}
//
function drop(e) {
e.stopPropagation();
e.preventDefault();
var dt = e.dataTransfer;
var files = dt.files;
handleFiles(files);
}
//
function handleFiles(files) {
for (var i = 0; i < files.length; i++) {
// get the next file that the user selected
var file = files[i];
var imageType = /image.*/;
// don't try to process non-images
if (!file.type.match(imageType)) {
continue;
}
// a seed img element for the FileReader
var img = document.createElement("img");
img.classList.add("obj");
img.file = file;
// get an image file from the user
// this uses drag/drop, but you could substitute file-browsing
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
aImg.onload = function() {
// draw the aImg onto the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = aImg.width;
canvas.height = aImg.height;
ctx.drawImage(aImg, 0, 0);
// make the jpeg image
var newImg = new Image();
newImg.onload = function() {
newImg.id = "newest";
document.body.appendChild(newImg);
}
newImg.src = canvas.toDataURL('image/jpeg');
}
// e.target.result is a dataURL for the image
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
} // end for
} // end handleFiles
body {
background-color: ivory;
}
canvas {
border: 1px solid red;
}
#dropzone {
border: 1px solid blue;
width: 300px;
height: 300px;
}
<h4>Drag file(s) from desktop to blue dropzone.<br>Only image files will be processed.</h4>
<div id="dropzone"></div>
<div id="preview"></div>

Export Canvas content to PDF

I am working on something using HTML5 Canvas.
It's all working great, except right now, I can export the canvas content to PNG using Canvas2image. But I would like to export it to PDF. I've made some research and I'm pretty sure it's possible...but I can't seem to understand what I need to change in my code to make it work. I've read about a plugin called pdf.js...but I can't figure out how to implent it in my code.
First part :
function showDownloadText() {
document.getElementById("buttoncontainer").style.display = "none";
document.getElementById("textdownload").style.display = "block";
}
function hideDownloadText() {
document.getElementById("buttoncontainer").style.display = "block";
document.getElementById("textdownload").style.display = "none";
}
function convertCanvas(strType) {
if (strType == "PNG")
var oImg = Canvas2Image.saveAsPNG(oCanvas, true);
if (strType == "BMP")
var oImg = Canvas2Image.saveAsBMP(oCanvas, true);
if (strType == "JPEG")
var oImg = Canvas2Image.saveAsJPEG(oCanvas, true);
if (!oImg) {
alert("Sorry, this browser is not capable of saving " + strType + " files!");
return false;
}
oImg.id = "canvasimage";
oImg.style.border = oCanvas.style.border;
oCanvas.parentNode.replaceChild(oImg, oCanvas);
showDownloadText();
}
And the JS to that saves the image :
document.getElementById("convertpngbtn").onclick = function() {
convertCanvas("PNG");
}
document.getElementById("resetbtn").onclick = function() {
var oImg = document.getElementById("canvasimage");
oImg.parentNode.replaceChild(oCanvas, oImg);
hideDownloadText();
}
}
You need to use 2 plugins for this:
1) jsPDF
2) canvas-toBlob.js
Then add this piece of code to generate light weight PDF:
canvas.toBlob(function (blob) {
var url = window.URL || window.webkitURL;
var imgSrc = url.createObjectURL(blob);
var img = new Image();
img.src = imgSrc;
img.onload = function () {
var pdf = new jsPDF('p', 'px', [img.height, img.width]);
pdf.addImage(img, 0, 0, img.width, img.height);
pdf.save(fileName + '.pdf');
};
});
Look at this links:
http://www.codeproject.com/Questions/385045/export-html5-webpage-including-canvas-to-pdf
http://badassjs.com/post/708922912/pdf-js-create-pdfs-in-javascript
Most probably it will do the work you need
This jspdf is only useful in saving the file in the browser but we can't use that PDF generated to send to the server

Categories

Resources