This is my code for showing a image from user local machine, but it sometimes doesn't work for the first time. Specially when (on mobile) user take a picture from camera.
It almost always doesn't work for the first time that user select his image.
I use Image() to get the width and height of image for aspectRatio of resizable.
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Image</title>
<style>
* {
padding: 0;
margin: 0;
}
body {
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.select-img {
width: 450px;
height: 250px;
border-radius: 10px;
cursor: pointer;
border: 3px dashed gray;
display: flex;
justify-content: center;
align-items: center;
font-family: sans-serif;
font-size: 25px;
}
#image {
display: none;
}
</style>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
</head>
<body>
<div class="select-img">
<p>Select Image</p>
</div>
<img id="image">
<script>
function upload (file) {
var fr = new FileReader();
fr.onload = function (event) {
var src = event.target.result;
var img = new Image();
img.onload = function () {
$('.select-img').remove();
$('#image').css('display', 'block').attr('src', src).resizable({ aspectRatio: this.width / this.height });
};
img.src = src;
};
fr.readAsDataURL(file);
}
$('.select-img').click(function () {
var fileInput = $(document.createElement("input"));
fileInput.attr('type', 'file');
fileInput.attr('accept', 'image/*');
fileInput.trigger('click');
$(fileInput).on('change', function (ev) {
upload(ev.target.files[0]);
});
return false;
});
</script>
</body>
</html>
Did some intitial testing via FireFox on desktop and Chrome on Android. Both work properly to display the image:
Working Example: https://jsfiddle.net/Twisty/188x0w0u - for mobile testing, use: https://jsfiddle.net/Twisty/188x0w0u/show
JavaScript
$(function() {
function upload(file) {
var fr = new FileReader();
fr.onload = function(event) {
var src = event.target.result;
var img = new Image();
img.onload = function() {
$('.select-img').remove();
$('#image').css('display', 'block').attr('src', src).resizable({
aspectRatio: this.width / this.height
});
};
img.src = src;
};
fr.readAsDataURL(file);
}
$('.select-img').click(function() {
var fileInput = $("<input>", {
type: "file",
accept: "image/*"
});
fileInput.trigger('click');
fileInput.on('change', function(ev) {
upload(ev.target.files[0]);
});
return false;
});
});
Minor switches to code to make better use of jQuery. this worked in both capturing a photo from camera and selecting photo from documents on the mobile device.
Resizing fails, and for me this was expected. Add Touch punch:
https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js
New Test: https://jsfiddle.net/Twisty/188x0w0u/2/
Mobile: https://jsfiddle.net/Twisty/188x0w0u/2/show/
Now the .resizable() works on mobile too.
Related
I am trying to get an input type-file, append it to unordered list and make it show up in browser
But it's not showing up and browser not showing any errors
Please help. I am trying to solve this problem already 3 days. I recently started coding, please don't make fun of me
This is my own project in order to learn better JavaScript
My html
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>javascripttutorial</title>
<style>
.name-div {
color: aliceblue;
}
.photo-div {
color: aliceblue;
}
.date-div {
color: aliceblue;
}
.box-1 {
border: 1px solid black;
padding: 10px;
display: flex;
flex-direction: column;
height: 500px;
width: 100px;
float: left;
}
.box-2 {
border: 1px solid black;
padding: 10px;
display: flex;
flex-direction: column;
height: 500px;
width: 200px;
float: left;
}
.box-3 {
border: 1px solid black;
padding: 10px;
display: flex;
flex-direction: column;
height: 500px;
width: 150px;
float: left;
}
body {
margin-left: 20px;
margin-right: 20px;
}</style> <script src="script.js"></script></head><body>
<div style="margin: 10px;" class="name-div">
<input id="input-name" type="text" placeholder="Your name">
</div>
<div style="margin: 10px;" class="photo-div">
<input id="input-photo" type="file" onchange="previewFile()"><br>
<img src="" height="100" alt="Image preview...">
</div>
<div style="margin: 10px;" class="date-div">
<input id="input-date" type="date" placeholder="Your birthday">
</div>
<div style="margin: 10px;" class="button-div">
<button id="button">Submit</button>
</div>
<span class="box-1">
<ul id="messages-1">Name: </ul>
</span>
<span class="box-2">
<ul id="messages-2">Photo: </ul>
</span>
<span class="box-3">
<ul id="messages-3">Date: </ul>
</span>
<script async src="script.js"></script></body></html>>
My script
window.onload=function(){
var inputName = document.getElementById('input-name');
var inputPhoto = document.getElementById('input-photo');
var inputDate = document.getElementById('input-date');
var button = document.getElementById('button');
var messages1 = document.getElementById('messages-1');
var messages2 = document.getElementById('messages-2');
var messages3 = document.getElementById('messages-3');
button.addEventListener("click", function(){
var newMessage1 = document.createElement("li");
var newMessage2 = document.createElement("li");
var photo = document.createElement("img");
var newMessage3 = document.createElement("li");
newMessage1.innerHTML = inputName.value;
photo.setAttribute("style", "height: 30px; widht: 30px;");
var reader1 = new FileReader();
reader1.addEventListener("onloadend", function(){
reader1.readAsDataURL(inputPhoto);
photo.src = reader1.result;
});
newMessage3.innerHTML = inputDate.value;
messages1.appendChild(newMessage1);
messages2.appendChild(newMessage2)
messages3.appendChild(newMessage3);
newMessage2.appendChild(photo);
inputName.value = "";
inputDate.value = "";
});
}
function previewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}
Steps to Follow
Listen to the change event fire by the image file upload input on an image upload.
Grab the file from the parameter that receives to the event listener callback.
Then pass it to the FileReader.
That's it in here.
inputPhoto.addEventListener("change", (e) => {
var file = e.target.files[0];
fileReader.readAsDataURL(file);
});
Now listen to the load event fire by the FileReader.
Get the base64 from the parameter.
Create an image element to preview the uploaded image.
Then set the base64 to that image src attribute.
fileReader.addEventListener("load", (e) => {
var imgUploadWrap = document.getElementsByClassName("photo-div")[0];
var img = document.createElement("img");
var base64 = e.target.result;
img.setAttribute("id", "uploaded-img");
img.height = 100;
img.src = base64;
imgUploadWrap.append(img);
});
Notes:
I create a new image element on upload because it will be easier to reset it.
If you listen to the load event, not loadend, then you don't have to handle the file empty scenario because the load event is fired only if the upload is successful.
Finally when clicking the submit button, set the preview image element's src attribute to the image element inside the message.
if (uploadedImg) {
photo.height = 60;
photo.src = uploadedImg.src;
uploadedImg.remove();
}
Full Code - https://codesandbox.io/s/input-type-file-not-showing-up-even-with-filereader-71891729-u5bvft?file=/script.js
I am trying to use this code to resize images and print them on an html canvas to modify them later:
var wth = img.clientHeight / img.clientWidth;
img.width=300;
img.height=300 * wth;
ctx.drawImage(img, 0, 0);
However, this does not change the result on canvas. It still appears to be too large for the canvas.
When I use this code, as suggested in this question the image does not load at all. I don't know if I am using it wrong or something but it just doesn't work.
ctx.drawImage(img, 0, 0, 300, 300 * wth);
This is my code:
function preview_image(event)
{
var output = document.getElementById('output_image');
var reader = new FileReader();
var ctx = output.getContext('2d');
//output.src = "/loading.gif";
reader.onload = function()
{
//output.src = reader.result;
var img = new Image(); // Create new img element
img.src = reader.result; // Set source path
img.onload = function() {
var wth = img.clientHeight / img.clientWidth;
img.width=300;
img.height=300 * wth;
ctx.drawImage(img, 0, 0);
}
}
reader.readAsDataURL(event.target.files[0]);
}
body
{
width:100%;
margin:0 auto;
padding:0px;
font-family:helvetica;
background-color:#0B3861;
}
#wrapper
{
text-align:center;
margin:0 auto;
padding:0px;
width:995px;
margin: auto;
}
#output_image
{
margin: auto;
max-width:300px;
}
.editarea{
width: 50%;
background: #EC6C67;
margin: auto;
}
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ReturNull Photo Editor</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="wrapper">
<input type="file" accept="image/*" onchange="preview_image(event)"><br><br>
<div class="editarea"> <!--<img id="output_image" width="250">--> <canvas id="output_image" width="250"></canvas></div>
</div>
</body>
</html>
I changed arguments in ctx.drawImage function:
function preview_image(event)
{
var output = document.getElementById('output_image');
var reader = new FileReader();
var ctx = output.getContext('2d');
//output.src = "/loading.gif";
reader.onload = function()
{
//output.src = reader.result;
var img = new Image(); // Create new img element
img.src = reader.result; // Set source path
img.onload = function() {
var wth = img.clientHeight / img.clientWidth;
img.width=300;
img.height=300 * wth;
ctx.drawImage(img, (output.width / 2) - (img.width / 2), 0, img.width, output.height);
}
}
reader.readAsDataURL(event.target.files[0]);
}
body
{
width:100%;
margin:0 auto;
padding:0px;
font-family:helvetica;
background-color:#0B3861;
}
#wrapper
{
text-align:center;
margin:0 auto;
padding:0px;
width:995px;
margin: auto;
}
#output_image
{
margin: auto;
max-width:300px;
}
.editarea{
width: 50%;
background: #EC6C67;
margin: auto;
}
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ReturNull Photo Editor</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="wrapper">
<input type="file" accept="image/*" onchange="preview_image(event)"><br><br>
<div class="editarea"> <!--<img id="output_image" width="250">--> <canvas id="output_image" width="250"></canvas></div>
</div>
</body>
</html>
I am trying to combine two js scripts to allow a local jpeg to be viewed locally in browser on top of the camera feed with 80% opacity to make an AR tracing web app.
With the following code, it displays the webcam feed correctly but it doesn't display the uploaded overlaying the camera feed. I am trying to keep the code as simple as possible. The scripts work okay when using only one or the other, but not both at the same time.
Image viewer overlay JS:
$("input").change(function(e) {
for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
var file = e.originalEvent.srcElement.files[i];
var img = document.createElement("img");
var reader = new FileReader();
reader.onloadend = function() {
img.src = reader.result;
}
reader.readAsDataURL(file);
$("input").after(img);
}
});
Cam feed JS:
var constraints = { audio: false, video: { width: 300, height: 300 } };
navigator.mediaDevices.getUserMedia(constraints)
.then(function(mediaStream) {
var video = document.querySelector('video');
video.srcObject = mediaStream;
video.onloadedmetadata = function(e) {
video.play();
};
})
.catch(function(err) { console.log(err.name + ": " + err.message); }); // always check for errors at the end.
HTML:
<html>
<head>
<style>
img { opacity: 80%
}
</style>
<script src="camfeed.js"></script>
<script src="overlay.js"></script>
</head>
<body>
<video id="vid"></video>
<input type="file" accept="image"></input>
</body>
</html>
UPDATE: I made some modifications of the code following suggestions. No fix but I get error message in console Uncaught TypeError: Cannot read property 'addEventListener' of null
at window.onload (overlay.js:7).
Here's the current HTML:
<html>
<head>
<style>
.overlay {
position: absolute;
left: 0px;
top: 0px;
opacity: 25%;
z-index: -1;
}
img {
position: absolute;
left: 0px;
top: 0px;
opacity: 25%;
z-image: -1;
}
video {
position: absolute;
left: 0px;
top: 0px;
height: 720;
width: 1280;
z-index:-2;
}
input {
z-index: 1;
}
</style>
</head>
<body>
<video id="vid"></video>
<div id="overlay"></div>
<input type="file" id=fileInput" accept="image" value="pick a pic"></input>
<script src="camfeed.js"></script>
<script src="overlay.js"></script>
</body>
</html>
Here's the current overlay.js:
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('overlay');
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!"
}
});
}
Here's the current camfeed.js (working):
// Prefer camera resolution nearest to 1280x720.
var constraints = { audio: false, video: { width: 1280, height: 720, facingMode: "environment" }};
navigator.mediaDevices.getUserMedia(constraints).then(function(mediaStream) {
var video = document.querySelector('video');
video.srcObject = mediaStream;
video.onloadedmetadata = function(e) {
video.play();
};
})
.catch(function(err) { console.log(err.name + ": " + err.message); }); // always check for errors at the end.
I got it working. The cause of the issue seems to be that I didn't include the following jquery script code in index.html console error log show that it couldn't interpret the dollar sign ($)in the javascript scripts without jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
Here's the fully functional code:
index.html:
<html>
<head>
<style>
.overlay {
position: absolute;
left: 0px;
top: 0px;
opacity: 25%;
z-index: -1;
}
img {
position: absolute;
left: 0px;
top: 0px;
opacity: 25%;
z-index: -1;
}
video {
position: absolute;
left: 0px;
top: 0px;
height: auto;
width: 100%;
z-index:-2;
}
input {
z-index: 1;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<video id="vid"></video>
<input class="joint" type='file' id="imgInp" />
<img style="width:100%" id="blah" src="#" alt="image display error" />
<script src="camfeed.js"></script>
<script src="overlay.js"></script>
</body>
</html>
overlay.js:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
camfeed.js:
// Prefer camera resolution nearest to 1280x720.
var constraints = { audio: false, video: { width: 1280, height: 720, facingMode: "environment" }};
navigator.mediaDevices.getUserMedia(constraints).then(function(mediaStream) {
var video = document.querySelector('video');
video.srcObject = mediaStream;
video.onloadedmetadata = function(e) {
video.play();
};
})
.catch(function(err) { console.log(err.name + ": " + err.message); }); // always check for errors at the end.
The end result is a helpful AR web app for tracing photos. Thanks for the tips.
I am using basic html input file uploader to upload image file, and div 'editor-image-1' that is preview of uploaded image. I am trying to handle this image previes with following code, but div does not change its background. Console log 'success' is being triggered, but image is not being displayed:
$("#editor-upload-1").change(function() {
$('#editor-image-1').css('background', "#FFF");
var file = this.files[0];
var imagefile = file.type;
var valid = ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==valid[0]) || (imagefile==valid[1]) || (imagefile==valid[2]))) {
$('#editor-image-1').css('background', "#F00");
alert("Wrong image format");
return false;
} else {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
function imageIsLoaded(e) {
console.log("success");
$('#editor-image-1').css('background', 'url("' + e.target.result + '")');
};
This works fine
There may be lot of failure
plz refer below code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>functionality</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>
<body>
<style>
.wrapper {
width: 100%;
/* whatever width you want */
display: inline-block;
position: relative;
background-size: contain;
margin: 0 auto;
}
.wrapper:after {
padding-top: 75%;
/* this llama image is 800x600 so set the padding top % to match 600/800 = .75 */
display: block;
content: '';
}
.main {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
color: black;
text-align: center;
margin-top: 5%;
}
</style>
<input type="file" id="editor-upload-1">
<div class="wrapper">
<div class="main" id="main">
</div>
</div>
<script>
$(function(){
$("#editor-upload-1").change(function() {
$('#main').css('background', "#FFF");
var file = this.files[0];
var imagefile = file.type;
var valid = ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==valid[0]) || (imagefile==valid[1]) || (imagefile==valid[2]))) {
$('#main').css('background', "#F00");
alert("Wrong image format");
return false;
} else {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
console.log("success");
$('#main').css('background', 'url("' + e.target.result + '")');
$('#main').css('top center no-repeat;');
};
</script>
</body>
</html>
I know this question has been asked more than once, but the answers I have found don't seem to apply to my situation... I am very novice at JavaScript, and even more so at debugging it. I am trying to lean by working through an online tutorial, but when I tried the onclick event, everything appears to be null at first - the function is supposed to resize the canvas and place the image in the top left corner on the first click. What is does is resizes the canvas on the first click, then on the 3rd click, adds the image... Since I am not calling on the style or display (to my knowledge), and there are no conditional statements in the function, I'm not sure why this is happening. I also tried to link the function instead of inline as suggested by another post, but to no avail... I am using Chrome. Any input would be greatly appreciated!
HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="js/main.js"></script>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<canvas id="gameCanvas" onclick="changeCanvasSize(this);" width = "400" height = "300"></canvas>
</body>
</html>
js:
function changeCanvasSize()
{
var gameCanvas = document.getElementById("gameCanvas");
var avatarImage = new Image();
gameCanvas.width = 600;
gameCanvas.height = 800;
avatarImage.src = "img/avatar.png";
gameCanvas.getContext("2d").drawImage(avatarImage, 0, 0);
}
css:
body {
background: #ffffff;
text-align: center;
padding: 20px;
color: #575757;
font: 14px/21px Arial,Helvetica,sans-serif;
}
a {
color: #B93F14;
}
a:hover {
text-decoration: none;
}
ol {
width: 600px;
text-align: left;
margin: 15px auto
}
canvas {
border: 1px solid black;
}
you have to wait for the image to load before inserting it:
function changeCanvasSize()
{
var gameCanvas = document.getElementById("gameCanvas");
var avatarImage = new Image();
gameCanvas.width = 600;
gameCanvas.height = 800;
avatarImage.src = "img/avatar.png";
avatarImage.onload = function() {
gameCanvas.getContext("2d").drawImage(avatarImage, 0, 0);
}
}