I have an input->type->file button which allow users to upload images. I am trying to preview the image before they can submit(upload) it. Can anyone help me solve, how can I re-size the image (before clicking submit) to fit the div (for the preview).
css
#preview_box{
margin-top:10px;
margin-left:10px;
float:left;
display:inline;
text-align:center;
height:408px;
width:490px;
position:relative;
border: 1px solid #adadad; /* stroke */
background-color: #fff; /* layer fill content */
-moz-box-shadow: 0 1px 6px rgba(0,0,0,.22); /* drop shadow */
-webkit-box-shadow: 0 1px 6px rgba(0,0,0,.22); /* drop shadow */
box-shadow: 0 1px 6px rgba(0,0,0,.22); /* drop shadow */
}
html
<div id="preview_box">This is a preview</div>
<form id="imageform" enctype="multipart/form-data" method="post" action="/help/upload.php">
<input name="photoimg" id="photoimg" type="file"/>
</form>
jquery
$("input[name='photoimg']").on("change", function(){
var files = !!this.files ? this.files : [];
// If no files were selected, or no FileReader support, return
if ( !files.length || !window.FileReader ) return;
// Only proceed if the selected file is an image
if ( /^image/.test( files[0].type ) ) {
// Create a new instance of the FileReader
reader = new FileReader();
// Read the local file as a DataURL
reader.readAsDataURL( files[0] );
// When loaded, set image data as background of page
reader.onloadend = function(){
$("#preview_box").css("background-image", "url(" + this.result + ")");
}
}
});
Thanks. (it will be great if I can keep the aspect-ratio when re-sizing the image)