Div background preview is not displayed after uploading image file - javascript

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>

Related

Javascript image object does not resize on canvas

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>

HTML5 + 2 JS Scripts only working separately - camera and local file input

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.

how could I drag my photo to another dropbox after my photo has been seen previewed?

what I would like to do is that the preview becomes draggable and moves to another dropbox
make img source" " moves(drag) to another dropbox area
<script>
function handleFiles(files) {
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (!file.type.startsWith('image/')){ continue }
const img = document.createElement("img");
img.classList.add("obj");
img.file = file;
preview.appendChild(img); // Assuming that "preview" is the div output where the content will be displayed.
const reader = new FileReader();
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
reader.readAsDataURL(file);
}
}```
</script>
How could I move to another area after my picture is in the preview
Using the java script display the image in div called 'preview'. and enable the functionality to drag the image in Drop Box container using the jQuery draggable & droppable function.
window.onload = function(){
//For example put some image in array
arrayfile = ['https://www.w3schools.com/html/pic_trulli.jpg', 'https://www.w3schools.com/html/img_girl.jpg'];
handleFiles(arrayfile);
function handleFiles(files) {
for (let i = 0; i < files.length; i++) {
const file = files[i];
var img = document.createElement("IMG");
img.setAttribute("src",file);
img.classList.add("child");
img.setAttribute("width", "304");
img.setAttribute("height", "228");
img.setAttribute("alt", "image alt");
img.setAttribute("width", "100");
img.setAttribute("height", "100");
//append the image in preview div
document.getElementById('preview').appendChild(img);
}
}
//Use the jquery draggable & droppable function
$(".child").draggable({
revert: true
});
//use container to drop the image
$(".container").droppable({
accept: '.child',
drop: function(event, ui) {
ui.helper.data('dropped', true);
$(this).append($(ui.draggable));
}
});
}
.container{
border:1px solid grey;
width: 250px; /*can be in percentage also.*/
height: 250px;
margin: 0px auto;
padding: 10px;
position: relative;
text-align:center;
float:left;
margin-left:20px;
}
.child {
padding: 2px;
border: 1px solid black;
margin: 5px;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!-- Preview div---->
<div id="preview" class="container" target="child1">
</div>
<!-- container to drop the Preview Image -->
<div class="container">
</div>

Show local image by JavaScript (mobile camera)

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.

Javascript drag and drop on leave doesn't work correctly

I am trying to implement a drag and drop image upload similar functionality to imgur.com.
You drag an image from your desktop and a big overlay div with the word 'upload' appears as you drag over your document.
My problem is that when I drag over the actual word 'upload' inside an h1 tag the screen flickers. This is happening because I have an event for dragleave to remove the overlay div with the upload h1 tag however I don't know how to fix it.
You can see the problem in action here: JS Fiddle, just drag any image from your desktop to the document and hover over the word 'upload' you'll see what I'm talking about. Any help would be appreciated.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Drag and Drop</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
</head>
<body>
<div id="upload-global-drop-overlay" style="display: none;"><h1>upload</h1></div>
</body>
</html>​
Javascript code:
$(document).on('dragover', function () {
$('#upload-global-drop-overlay').css({'display': 'block'});
});
$('#upload-global-drop-overlay').on('dragleave', function () {
$('#upload-global-drop-overlay').css({'display': 'none'});
});
$(document).on('drop', function (e) {
$('#upload-global-drop-overlay').css({'display': 'none'});
e.preventDefault();
});
​
Hey hopefully you found an answer to this, if not here is a little example that looks like imgur in my oppinion, using your code.
jsFiddle: http://jsfiddle.net/JUBwS/74/
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Drag and Drop</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
</head>
<body>
<div id="upload-global-drop-overlay" style="display: none;"><h1>upload</h1></div>
</body>
</html>​
CSS:
#upload-global-drop-overlay {
background: none repeat scroll 0 0 #424242;
height: 100%;
width: 100%;
position: fixed;
top: 0;
left: 0;
opacity: .8;
filter: alpha(opacity=80);
-moz-opacity: .8;
z-index: 10001;
display: none;
}
#upload-global-drop-overlay h1 {
font-size: 72pt;
display: block;
position: absolute;
line-height: 50px;
top: 50%;
left: 50%;
margin: -82px 0 0 -180px;
text-shadow: 3px 3px 4px black;
color: white;
z-index: -1;
}​
Javascript:
var isDragging = null;
$(document).on('dragover', function () {
if(isDragging==null)
doDrag();
isDragging = true;
});
$(document).on('drop', function (e) {
e.preventDefault();
isDragging = false;
});
$(document).on('dragleave', function (e) {
isDragging = false;
});
var timerId=0;
function doDrag()
{
timerId = setInterval(function()
{
if(isDragging)
$('#upload-global-drop-overlay').fadeIn(500);
else
{
$('#upload-global-drop-overlay').fadeOut(500);
isDragging = null;
clearInterval(timerId);
}
},200);
}​
This sample uses timers, but it is active only when something is being dragged into the form. I am certainly going to use this in the future.
I actually found another solution, I think it's a bit simpler because it doesn't use setInterval. And I've implemented the actual drag and drop functionality for anyone interested.
The whole working example with drag and drop functionality is available below.
jsFiddle - Demo: http://jsfiddle.net/6SV9P/1/
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Drag and Drop</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
</head>
<body>
<div id="upload-global-drop-overlay" style="display: none;"><h1>upload</h1</div>
<div id="image"></div>
</body>
</html>​
CSS:
#upload-global-drop-overlay {
background: none repeat scroll 0 0 #424242;
height: 100%;
width: 100%;
position: fixed;
top: 0;
left: 0;
opacity: .8;
filter: alpha(opacity=80);
-moz-opacity: .8;
z-index: 10001;
display: none;
}
#upload-global-drop-overlay h1 {
font-size: 72pt;
display: block;
position: absolute;
line-height: 50px;
top: 50%;
left: 50%;
margin: -82px 0 0 -180px;
text-shadow: 3px 3px 4px black;
color: white;
z-index: -1;
}​
JS:
var dragDropFromDesktop = (function ($) {
$(document).on('dragenter', function () {
$('#upload-global-drop-overlay').fadeIn(200)
});
$('#upload-global-drop-overlay').on('dragleave', function (e) {
if (e.originalEvent.pageX < 10 || e.originalEvent.pageY < 10 || $(window).width() - e.originalEvent.pageX < 10 || $(window).height - e.originalEvent.pageY < 10) {
$("#upload-global-drop-overlay").fadeOut(200);
}
});
$('#upload-global-drop-overlay').on('dragover', function (e) {
e.stopPropagation();
e.preventDefault();
});
// Handle dropped image file - only Firefox and Google Chrome
$('#upload-global-drop-overlay').on('drop', function (e) {
$('#upload-global-drop-overlay').fadeOut(200);
var files = e.originalEvent.dataTransfer.files;
if (files === undefined) {
alert('Your browser does not support file Drag and Drop!')
} else {
var file = files[0];
if (typeof FileReader !== "undefined" && file.type.indexOf("image") != -1) {
var reader = new FileReader();
reader.onload = function (evt) {
var img = new Image();
img.src = evt.target.result;
$('#image').html('<img src="' + img.src + '">');
};
reader.readAsDataURL(file);
}
}
e.preventDefault();
e.stopPropagation();
});
})(jQuery);​

Categories