Basically I have a form which inside it I have an image box with a file input, now i need to show the the picture choosen from file input and show it in my image box without the form to submit.
i found a tutorial which says:
<!DOCTYPE html>
<html>
<head>
<script>
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
function readURL(input) {
if (input.files && input.files[0]) {
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
alert(input.val());
});
</script>
</head>
<body>
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
</body>
</html>
but this don't show the select image in my image box.
try this sample 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);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
javascript at Question appears to return expected result. The issue is placement of <script> element or not utilizing .ready(). Also, input is not defined within change event. You can substitute this.value for input.val() within change event handler as parameter to alert() call.
Placing <script> element beneath <form> element at html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
</head>
<body>
<form id="form1" runat="server">
<input type="file" id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
<script>
var reader = new FileReader();
reader.onload = function(e) {
$('#blah').attr('src', e.target.result);
}
function readURL(input) {
if (input.files && input.files[0]) {
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function() {
readURL(this);
alert(this.value);
});
</script>
</body>
</html>
using .ready() with <script> element remaining as child of <head> element
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<script>
$().ready(function() {
var reader = new FileReader();
reader.onload = function(e) {
$('#blah').attr('src', e.target.result);
}
function readURL(input) {
if (input.files && input.files[0]) {
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function() {
readURL(this);
alert(this.value);
});
})
</script>
</head>
<body>
<form id="form1" runat="server">
<input type="file" id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
</body>
</html>
Related
I am trying to crop image and send the cropped data to server side. I am using imgareaselect plugin. I get the coordinates of selection but could not crop the image. All the solutions available on internet is to preview cropped image using css. But how can I get the cropped data? No need of preview the cropped image. My code is
cropw = $('#cropimg').imgAreaSelect({
maxWidth: 300, maxHeight: 300,
aspectRatio: '1:1',
instance: true,
handles: true,
onSelectEnd: function (img, selection) {
x1 = selection.x1;
y1 = selection.y1;
x2 = selection.x2;
y2 = selection.y2;
}
});
Hey #Shahbaz I was trying out a solution for you using cropper.js.
This is what you can do
Download cropper.js from here
//link the js files
<head>
<script src="jquery.js"></script> // optional
<link href="cropper.min.css" rel="stylesheet">
<script src="cropper.min.js"></script>
</head>
Body
<input type="file" name="image" id="image" onchange="readURL(this);"/>
<div class="image_container">
<img id="blah" src="#" alt="your image" />
</div>
<div id="cropped_result"></div> // Cropped image to display (only if u want)
<button id="crop_button">Crop</button> // Will trigger crop event
Javascript
<script type="text/javascript" defer>
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]);
setTimeout(initCropper, 1000);
}
}
function initCropper(){
var image = document.getElementById('blah');
var cropper = new Cropper(image, {
aspectRatio: 1 / 1,
crop: function(e) {
console.log(e.detail.x);
console.log(e.detail.y);
}
});
// On crop button clicked
document.getElementById('crop_button').addEventListener('click', function(){
var imgurl = cropper.getCroppedCanvas().toDataURL();
var img = document.createElement("img");
img.src = imgurl;
document.getElementById("cropped_result").appendChild(img);
/* ---------------- SEND IMAGE TO THE SERVER-------------------------
cropper.getCroppedCanvas().toBlob(function (blob) {
var formData = new FormData();
formData.append('croppedImage', blob);
// Use `jQuery.ajax` method
$.ajax('/path/to/upload', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function () {
console.log('Upload success');
},
error: function () {
console.log('Upload error');
}
});
});
----------------------------------------------------*/
})
}
</script>
Hope this helps. Thanks.
Added this one based on the accepted answer, In case anyone is using the jquery wrapper for cropper
let ICropper = (function($) {
let $cropperCanvasImage = $('#cropper-canvas-image');
return {
readUrl,
cropImage
}
function readUrl(input) {
if (input.files && input.files[0]) {
let reader = new FileReader();
reader.onload = function(e) {
$cropperCanvasImage.attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
setTimeout(initCropper, 1000);
}
}
function initCropper() {
$cropperCanvasImage.cropper({
aspectRatio: 1 / 1
});
}
function cropImage() {
let imgUrl = $cropperCanvasImage.data('cropper').getCroppedCanvas().toDataURL();
let img = document.createElement("img");
img.src = imgUrl;
$("#cropped-result").append(img);
}
})(jQuery)
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.1/cropper.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script name="jquery-croper-script">
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(require("jquery"),require("cropperjs")):"function"==typeof define&&define.amd?define(["jquery","cropperjs"],r):r(e.jQuery,e.Cropper)}(this,function(c,s){"use strict";if(c=c&&c.hasOwnProperty("default")?c.default:c,s=s&&s.hasOwnProperty("default")?s.default:s,c.fn){var e=c.fn.cropper,d="cropper";c.fn.cropper=function(p){for(var e=arguments.length,a=Array(1<e?e-1:0),r=1;r<e;r++)a[r-1]=arguments[r];var u=void 0;return this.each(function(e,r){var t=c(r),n="destroy"===p,o=t.data(d);if(!o){if(n)return;var f=c.extend({},t.data(),c.isPlainObject(p)&&p);o=new s(r,f),t.data(d,o)}if("string"==typeof p){var i=o[p];c.isFunction(i)&&((u=i.apply(o,a))===o&&(u=void 0),n&&t.removeData(d))}}),void 0!==u?u:this},c.fn.cropper.Constructor=s,c.fn.cropper.setDefaults=s.setDefaults,c.fn.cropper.noConflict=function(){return c.fn.cropper=e,this}}});
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.1/cropper.min.css" />
<input type="file" name="source-image" id="sourceImage" onchange="ICropper.readUrl(this);" />
<div class="image-container">
<img id="cropper-canvas-image" src="#" alt="your image" />
</div>
<div id="cropped-result"></div>
<button onclick="ICropper.cropImage(this)">Crop</button>
Did you try using a crop plugin for Jquery, like:
https://fengyuanchen.github.io/cropper/
You have to import the scripts in your page:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$targ_w = $targ_h = 150;
$jpeg_quality = 90;
$src = 'demo_files/pool.jpg';
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);
header('Content-type: image/jpeg');
imagejpeg($dst_r,null,$jpeg_quality);
exit;
}
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://deepliquid.com/Jcrop/js/jquery.Jcrop.min.js"></script>
<script src="../js/jquery.Jcrop.js"></script>
<link rel="stylesheet" href="../css/jquery.Jcrop.css" type="text/css" />
<link rel="stylesheet" href="demo_files/demos.css" type="text/css" />
<script language="Javascript">
$(function(){
$('#cropbox').Jcrop({
aspectRatio: 1,
onSelect: updateCoords
});
});
function updateCoords(c)
{
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
};
function checkCoords()
{
if (parseInt($('#w').val())) return true;
alert('Selecione a área para recorte.');
return false;
};
</script>
</head>
<body>
<div id="outer">
<div class="jcExample">
<div class="article">
<h1>Crop jQuery</h1>
<img src="demo_files/pool.jpg" id="cropbox" />
<form action="crop.php" method="post" onsubmit="return checkCoords();">
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<input type="submit" value="Crop Image" />
</form>
</div>
</div>
</div>
</body>
</html>
I have a button called f1 and I want it to display the value of the image that the user puts when they select an image. For example, when you select an image it'll display on the screen but I also want it to display on the button with proper width and height attributes, how would I do that? I've tried the document.getElementById("f1").innerHTML = input.value; but that only displays the file path, not the actual image. I appreciate the help.
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img')
.attr('src', e.target.result)
.width(250)
.height(200);
};
reader.readAsDataURL(input.files[0]);
const f1 = document.getElementById("f1").innerHTML = input.value;
}
}
#f1 {
width:50px;
height:40px;
}
#img {
position:relative;
left:275px;
top:200px;
}
<!DOCTYPE html>
<html>
<head>
<title>Filter Image</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<input type='file' id="file" onchange="readURL(this);" accept="image/gif, image/jpeg, image/png">
<img id="img"/>
<button id = "f1"></button>
</body>
</html>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img')
.attr('src', e.target.result)
.width(50)
.height(50);
};
reader.readAsDataURL(input.files[0]);
}
}
<!DOCTYPE html>
<html>
<head>
<title>Filter Image</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<input type='file' id="file" onchange="readURL(this);" accept="image/gif, image/jpeg, image/png">
<button id = "f1"><img id="img"/></button>
</body>
</html>
I am trying to create a form for uploading an image and displaying a small preview of the image after selecting it. The preview is failing to display.
HTML code:
<label for="">Image</label>
<input type="file" class="form-control" name="image" id="img">
<img src="#" id="imgPreview" alt="">
JS code:
function readURL(input) {
if(input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$("#imgPreview").attr('src', e.target.result).width(100).height(100);
}
reader.readAsDataURL(input.files[0]);
}
$("#img").change(function() {
readURL(this);
});
}
Your change function on #img is never called because it inside your readURL function. You just need to put change function outside and everything good to go.
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$("#imgPreview")
.attr("src", e.target.result)
.width(100)
.height(100);
};
reader.readAsDataURL(input.files[0]);
}
}
$("#img").change(function() {
readURL(this);
});
Working demo here
You need to put change event of #img in the page init.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<label for="">Image</label>
<input type="file" class="form-control" name="image" id="img">
<img src="#" id="imgPreview" alt="">
<script>
$(function () {
$('#img').change(function () {
readURL(this);
});
})
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$("#imgPreview").attr('src', e.target.result).width(100).height(100);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
</body>
</html>
I want to add an image in canvas by using browse button. I tried to do something, I can use browse button but not add an image in canvas.How can I do?
<div style="float:left;"><canvas id="c" width="800" height="800"></canvas></div>
<p onclick="jQuery('#file').trigger('click');">Select a file</p>
<input type="file" id="file" name="file" />
Something like this?
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.js"></script>
</head>
<body>
<script>
$(function() {
$('#file-input').change(function(e) {
var file = e.target.files[0],
imageType = /image.*/;
if (!file.type.match(imageType))
return;
var reader = new FileReader();
reader.onload = loadFile;
reader.readAsDataURL(file);
});
function loadFile(e) {
var $img = $('<img>', { src: e.target.result });
var canvas = $('#canvas')[0];
var context = canvas.getContext('2d');
$img.load(function() {
context.drawImage(this, 0, 0);
});
}
});
</script>
<div style="float:bottom"><input type="file" id="file-input"><div>
<div style="float:left">
<canvas id="canvas" width="800px" height="800px"></canvas>
</div>
</body>
</html>
Have the followig questions and need answers regarding the following script that will Preview a Photo before upload. The script is from http://jsbin.com/uboqu3/edit#javascript,html
1) The script works for Firefox, no good for IE. How to make it works for IE?
2) It does not have a method to delete the photo. Needs something like a small image "X" installed on the Preview Photo, clicking this "X" will delete the photo. Can anyone supply this solution?
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img_prev')
.attr('src', e.target.result)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="img_prev" src="#" alt="your image" />
</body>
</html>
Demo
Tested on several browsers, Chrome, Fx, Safari 6 (could someone test 5?)
Works on my IE8 on XP without any changes in settings but as #Gunasekaran mentions later on this page you may need to
Open Tools->internet option-> security tab-> custom level - locate the setting "Include local directory path when uploading files to a server" and click on Enable.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Image preview</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
var blank="http://upload.wikimedia.org/wikipedia/commons/c/c0/Blank.gif";
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img_prev')
.attr('src', e.target.result)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
else {
var img = input.value;
$('#img_prev').attr('src',img).height(200);
}
$("#x").show().css("margin-right","10px");
}
$(document).ready(function() {
$("#x").click(function() {
$("#img_prev").attr("src",blank);
$("#x").hide();
});
});
</script>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
#x { display:none; position:relative; z-index:200; float:right}
#previewPane { display: inline-block; }
</style>
</head>
<body>
<section>
<input type='file' onchange="readURL(this);" /><br/>
<span id="previewPane">
<img id="img_prev" src="#" alt="your image" />
<span id="x">[X]</span>
</span>
</section>
</body>
</html>
Looks like this in IE8 on XP:
A newer method is createObjectURL which I have not implemented
Update You will need to add an onclick to clear the file input if you want to allow the user to select the same image twice (onchange does not trigger then)
HTML input file selection event not firing upon selecting the same file
This will not work on anything less that Internet Explorer 10 ... FileReader() support isn't introduced until IE10 .. it will work with Chrome 7 and Firefox 3.6
See the docs for support of FileReader or caniuse.com here
In reply to last response of #user1315468
IE8 needs a security settings change:
Open Tools->internet option-> security tab-> custom level
locate the setting "Include local directory path when uploading files to a server" and click on Enable.
After this change, you can reopen the browser with mplungjan's demo link.
Hope this helps.
**I have Pasted the complete working code for all browsers..
NOTE: sometimes Internet Explorer may block scripts,so inorder to view the image click on the prompt and "Allow blocked content".Below is the working code...**
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
</head>
<body>
<form name="form2">
<div>
<input type="file" name="myFile" id="myFile" onchange="readURL(this);"></input>
</div>
<div>
<img id="previewImg" src="#" />
</div>
</form>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#previewImg')
.attr('src', e.target.result)
.width(130);
}
reader.readAsDataURL(input.files[0]);
}else{
var filename = "";
filename = "file:\/\/"+input.value;
document.form2.previewImg.src=filename;
document.form2.previewImg.style.width="130px";
}
}
</script>
</body>
</html>
FileReader sounds great to read content of image or file.
But consider that file that you were reading was 20MB big, reading it as dataURL is going to create a JS object which is tat big. How do you avoid that ?
<img id="img1" alt="" runat="server"/>
<span id="x" ></span>
<asp:FileUpload runat="server" ID="FileUpload1" onchange="readURL(this)" />
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$("#imgRepresentImage").attr("src", e.target.result).width(200);
};
reader.readAsDataURL(input.files[0]);
} else {
var img = input.value;
$("#imgRepresentImage").attr("src", img).width(200);
}
$("#x").text('[X]');
}
$(document).ready(function () {
$("#x").click(function () {
$("#imgRepresentImage").attr("src", "").width(0);
$("#x").text('');
$("#representImageUpload").val('');
});
});
Worked for me :)