Limit image proportions with JavaScript - javascript

<input type="file" id="file" accept="image/gif, image/jpeg, image/png">
The HTML code is structured as follows.
In this case, if an image with a ratio of 1:1 is not entered in the input, I want to move to another page through JavaScript.

You basically need to add a handler for the input, and check if the height/width === 1, you can use this function to validate it:
const fileUpload = document.getElementById("file");
function validateImage(target) {
const reader = new FileReader();
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
const image = new Image();
image.src = e.target.result;
image.onload = function () {
const height = this.height;
const width = this.width;
if (height / width !== 1) {
console.log("ASPECT RATIO NOT 1:1");
window.location.href = "#otherpage"; // redirect
return false;
}
// do nothing
return true;
};
};
}
<input type="file" id="file" accept="image/gif, image/jpeg, image/png" onchange="validateImage(this)">
Note that this is a very simple validation, normally you would want to add error handlers (e.g. invalid file, broken image, etc.).

Related

How to get the dimensions of an image selected for a file input on the browser [duplicate]

This question already has answers here:
Check image width and height before upload with Javascript
(11 answers)
Closed 1 year ago.
I have an image upload box. Standard stuff:
<input id="image-upload-input" type="file" />
Once the user picks a file, I can access the contents and send it to my API over Axios like such:
const imageUploadInput = document.getElementById("image-upload-input");
const file = imageUploadInput.files[0];
if (!file) {
return;
}
const reader = new FileReader();
const component = this;
reader.onload = function (event) {
axios.post("upload/image", Buffer.from(event.target.result));
};
reader.readAsArrayBuffer(file);
However, I have some restrictions regarding dimensions and would like to check those on the client side.
I am fairly certain it can be done. I haven't tried it yet but I imagine if I just pop the data into an (ideally invisible) img tag with a data src attribute, that might work. Does anyone have any working code? Or a better way to do it?
adding something like this should work
imageUploadInput.onchange = function (event) {
const file = imageUploadInput.files[0];
if (!file) {
return;
}
const image = new Image();
image.onload = function() {
console.log(this.width, this.height);
}
image.src = URL.createObjectURL(file);
};

How do I find the src value of an image uploaded using fileReader?

I'm building a program that allows the user to choose an image to upload. Once the user chooses one, it triggers the previewFile() function, which uses FileReader to display the image.
Now I'm building a function that will download the same image that the user uploaded (and add some style changes). First, I created a new image element, but now I'm stuck, since I can't figure out how to reference the src value of the original image. Once I do get the src value, I can finish adding the styles, then download the edited image.
Here's what I have so far - can anyone help me out?
HTML:
<input type="file" onchange="previewFile()">
<img src="" alt="Preview File...">
JavaScript:
function previewFile() {
const preview = document.querySelector('img');
const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
And the function I need help with:
function createAndDownload() {
const editedImage = document.createElement('img');
/*
Here's where I need help: I need to figure out how to get the image src
from the original image, and set it equal to editedImage.src
*/
//add styles
//download editedImage
}
You assigned it this way:
const preview = document.querySelector('img');
preview.src = reader.result;
So you do the same thing to read it back:
const preview = document.querySelector('img');
const something = preview.src;

input type file, how to get image on screen?

<input hidden type="file" id="inpfile" accept="image/*">
$('#inpfile').change(function(){
var a = this.files[0];
var reader = new FileReader();
reader.readAsDataURL(a);
reader.onload = function (e) {
var imga = new Image();
imga.src = e.target.result;
}
});
Where is that image?
How can I really get it on screen and change its style?
When you do new Image() you create element in memory only, not in DOM. Create element <img> in DOM and use it instead
$(document).ready(function(){
var currentIndex = 1;
$('#inpfile').change(function(){
var reader = new FileReader();
reader.readAsDataURL(this.files[0]);
reader.onload = function (e) {
$('<img id="img' + currentIndex + '" class="img">') // jQuery will create new element if you pass not CSS selector, but expression, like in this case. Element still in memory
.attr('src', e.target.result) // Change src attribute of element to base64 encoded image source
.appendTo('.gallery'); // Append previous created element to <div class="gallery"> in DOM
currentIndex++; // Increment ID counter, so each element has unique ID
}
});
});
.img {
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="inpfile" accept="image/*"/>
<div class="gallery"></div>

JavaScript reading and previewing multiple images

I have found code for reading multiple images on the
internet.
Here is the code:
HTML
<input id="browse" type="file" onchange="previewFiles()" multiple>
JavaScript
function previewFiles() {
var preview = document.querySelector('#preview');
var files = document.querySelector('input[type=file]').files;
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
preview.appendChild( image );
}, false);
reader.readAsDataURL(file);
}
}
if (files) {
[].forEach.call(files, readAndPreview);
}
}
I have a problem with it, as I do not fully understand what is happening and why it does not preview/seems like it is storing multiple files.
The main problem in the included code is that there is no element with the id preview (ref: var preview = document.querySelector('#preview');)
Adding this and it will work. However, you can skip FileReader as it isn't needed. Instead treat the File as a Blob (they are essentially the same) and use createObjectURL() with it - the performance and the memory footprint are significant better in case you want to display a high amount of images.
document.querySelector('#browse').onchange = function() {
var preview = document.querySelector('#preview');
[].forEach.call(this.files, function(file) {
if (/image\/.*/.test(file.type)) { // use any image format the browser can read
var img = new Image;
img.onload = remURL; // to remove Object-URL after use
img.style.height = "100px"; // use style, "width" defaults to "auto"
img.src = (URL || webkitURL).createObjectURL(file);
preview.appendChild(img); // add image to preview container
}
});
function remURL() {(URL || webkitURL).revokeObjectURL(this.src)}
};
<input id="browse" type="file" multiple>
<div id=preview></div> <!-- an element with this ID was missing -->
Your final lines of code:
if (files) {
[].forEach.call(files, readAndPreview);
}
Should do nothing. It goes for each over an empty array.
I think you were trying to do something like:
files.forEach(readAndPreview)
Which would actually go over all of the files in the files array and call readAndPreview for them.

html5 select image and manipulate

I'm creating an app in which I want the user to upload an image with HTML5 <input type="file"/>
I know the browsers restrict getting the path of the image because of security, so i can't copy the image path and put it where ever I want.
Basically I want the user to submit an image, and I want to be able to manipulate the image by setting it as background-image of divs and putting the image in other places. hopefully by changing its source. This is not a server-side app so PHP or any server-side languages aren't an option.
EXAMPLE: If the user clicks a button, the image the user submited can be set as the background-image: url('image-path') of other divs and be applied to to other image tags.
Haven't tested across multiple browsers but can try something like this:
<input type="file" id="file">
$('#file').change(function(evt){
var img = $('<img/>');
var div = $('<div class="with-image"/>');
$(document.body).append(img);
$(document.body).append(div);
var reader = new FileReader();
reader.onload = (function(img) {
return function(ev) {
var image = ev.target.result;
img[0].src = image;
div.css('background-image', 'url("' + image + '")');
};
})(img);
var file = evt.target.files[0];
reader.readAsDataURL(file);
});
Here's a fiddle.
You would want to use the new File API for doing that, and that's really the only way of doing it without a server. Here is an example:
JSFiddle: http://jsfiddle.net/41w6f7n9/
;(function(window, undefined) {
var
doc = window.document,
userFile = doc.getElementById('userFile'),
divPreviews = doc.querySelectorAll('.preview'),
imgPreview = doc.getElementById('img-preview'),
// We will read the file as a Data URL.
fileReader = new FileReader();
var fileutil = {
init: function() {
userFile.addEventListener('change', function(e) {
fileutil.readFile(this.files[0]);
}, false);
},
readFile: function(file) {
var self = this;
// When done reading.
fileReader.onload = function(e) {
if (e.target.readyState === 2) { // 2 means DONE
self.preview(e.target.result);
}
};
// Start reading the file as a Data URL and wait to complete.
fileReader.readAsDataURL(file);
},
preview: function(imageURL) {
imgPreview.src = imageURL;
divPreviews[0].style.backgroundImage = 'url('+imageURL+')';
divPreviews[1].style.backgroundImage = 'url('+imageURL+')';
}
};
fileutil.init();
}(this));
The HTML:
<form>
<input type="file" id="userFile">
</form>
<h1>Image Preview</h1>
<img src="" width="400" id="img-preview">
<h1>Div preview 1</h1>
<div id="preview1" class="preview"></div>
<h1>Div preview 2</h1>
<div id="preview2" class="preview"></div>

Categories