Remove thumbnails create from input js - javascript

That is my problem :
I have written javascript code to create a thumbnail when a user uploads an image. I would now like to add a feature which allows a user to click on an "X" which will then deleted the image.
this is my code :
var imageLoader = document.getElementById('fUpload2');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas2');
var ctx = canvas.getContext('2d');
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
document.getElementById("imageCanvas2").style.height = canvas.height;
document.getElementById("imageCanvas2").style.maxWidth = "200px";
document.getElementById("imageCanvas2").style.maxHeight = "200px";
document.getElementById("imageCanvas2").style.border = "1px solid #000";
}
img.src = event.target.result;
var alte= canvas.height;
}
reader.readAsDataURL(e.target.files[0]);
}
.image-upload-gal > input {
display: none;
}
<div class="well">
<form class="form-horizontal" role="form" method="post" action="/ServiceUpload.php" enctype="multipart/form-data">
<div class="form-group" style="padding:14px;">
<div class="image-upload-gal" >
<label for="fUpload2">
Add foto
</label>
<input type="file" name="fUpload" id="fUpload2" />
<br>
<canvas id="imageCanvas2" ></canvas>
</div>
</div>
<button class="btn btn-primary pull-right" type="submit" value="f_upload" name="up" style="margin-top: -20px;">Submit Photo</button>
</form>
</div>
and that is another code ( i need 2 code is long story :D )
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('upload').addEventListener('change', handleFileSelect, false);
.thumb {
height: 180px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
input{
display:none;
}
<div class="image-upload" >
<label for="upload">
Add foto
</label>
<input type="file" id="upload" name="fUpload" />
<input type="hidden" name="up" value="f_upload" />
<output id="list"></output>
</div>
<button class="btn btn-primary pull-right" type="submit" value="newpost" name="NewPost" style="margin-top: -10px;">Submit</button>
</form>

just add an onclick event on a span containing a "x"
<span id="deleteImage">X</span>
Add the on Click handler then clear the canvas as you haven't saved the image anywhere else in that code
document.getElementById("deleteImage").onclick = function(){
canvas.clearRect(0, 0, canvas.width, canvas.height);
}
Edited.
if you want to clear the canvas directly below is how.
canvas = document.getElementById("imageCanvas2");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);

Related

How do I add a download button that will download the image after making changes?

I am working on a photo editor and I want to add a download button that will download the image after the user makes the necessary changes. The changes are working fine but I am not able to figure out how to download the image (Please keep in mind that the filter value depends on the user and is not constant). Does anyone have any ideas on how I can proceed further?
(P.S. I searched all over Stack Overflow and tried to implement every solution in my code but nothing's working)
Here's my HTML:
<!-- upload image button -->
<p><input type="file" accept="image/*" name="image" id="file" onchange="loadFile(event)" style="display: none;"></p>
<p><label for="file" style="cursor: pointer;" id="fileBtn">UPLOAD IMAGE</label></p>
<p><img id="img"></p>
<!-- side nav -->
<div class="sidenav">
<label for="filter-select">FILTER AND ADJUST</label>
<div class="slider">
<p style="color: aliceblue;">Sepia</p>
<input id="sepia" type="range" oninput="setSepia(this);" value="0" step="0.1" min="0" max="1"><span id="Amount" style="color: white;"> 0</span><br/><br>
<p style="color: aliceblue;">Grayscale</p>
<input id="Grayscale" type="range" oninput="setGs(this);" value="0" step="0.1" min="0" max="1"><span id="Amount2" style="color: white;"> 0</span><br/><br>
</div>
<label onclick = "RotateImg()">ROTATE</label>
<label onclick = "flipping()">FLIP</label>
<label onclick = "invert()">INVERT COLOURS</label>
<label onclick = "original()">ORIGINAL</label>
</div>
Here's my JavaScript:
function loadFile(event) {
var image = document.getElementById('img');
image.src = URL.createObjectURL(event.target.files[0]);
}
const options = {
sepia: 0,
grayscale: 0,
rotation: 0,
scale: 1,
invertVal: 0
};
function setSepia(e){
options.sepia = e.value;
document.getElementById('Amount').innerHTML= e.value;
redraw();
}
function setGs(e){
options.grayscale = e.value;
document.getElementById('Amount2').innerHTML= e.value;
redraw();
}
let rotation = 0;
function RotateImg(){
rotation += 90;
if (rotation == 360) {
rotation = 0;
}
options.rotation = rotation;
redraw();
}
let scale = 1
function flipping() {
scale -= 2
if (scale <= -2) {
scale = 1;
}
options.scale = scale;
redraw();
}
let invertVal = 0
function invert() {
invertVal += 100
if (invertVal > 100) {
invertVal = 0
}
options.invertVal = invertVal;
redraw();
}
function original() {
document.getElementById("img").style["webkitFilter"] ="sepia(0) grayscale(0)";
document.querySelector("img").style.transform = "rotate(0deg) scaleX(1)";
}
function redraw() {
document.getElementById("img").style["webkitFilter"] ="sepia(" + options.sepia + ") grayscale(" + options.grayscale + ");
document.querySelector("img").style.transform = `rotate(${options.rotation}deg) scaleX(${options.scale})`;
}
Your best bet would be to use the Canvas API to apply your edits and then use toDataURL to set up the download.
Here's a proof of concept fiddle:
<div id="container">
<img src="//placekitten.com/400/400" crossorigin="anonymous"/>
<canvas width="400" height="400" />
</div>
const canvas = document.querySelector('canvas');
const image = document.querySelector('img');
image.addEventListener('load', () => {
const ctx = canvas.getContext('2d');
// draw the image into the canvas with a sepia filter:
ctx.filter = 'sepia(1)';
ctx.drawImage(image, 0, 0);
// set up the download link
addDownload(canvas);
})
function addDownload (canvas) {
// create an <a>
const a = document.createElement('a');
// set it up to download instead of navigating
a.setAttribute('download', 'kitten.jpg');
a.innerHTML = "download";
// set the href to a data url for the image
a.href = canvas.toDataURL('image/jpg');
// append it to the dom
container.appendChild(a);
}

How can I get my function to display text over an image?

I'm trying to input text into a html form field (button) which will then be displayed on the same page over an image. Any advice of how I could get the two talking to each other would be really appreciated.
<canvas id="myCanvas" width="900" height="600" style="border:1px solid #404040;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var img =new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0, 900, 600);
function myFunction() {
document.getElementById("line1").innerHTML;
var line1 = document.getElementById("line1").value;
var line2 = document.getElementById("line2").value;
var line3 = document.getElementById("line3").value;
}
//the code below positions the overlaying text on the image
ctx.font = "bold 36px Times";
ctx.fillStyle = "black";
ctx.fillText ("line1",400,325);
ctx.fillText ("line2",400,375);
ctx.fillText ("line3",400,425);
}
//this is the image
img.src= "bus_red.gif"
</script>
//the code below allows the user to input text into boxes
<div>
<form>
<label for="line1">Enter your text: </label>
<input type="text" autocomplete="off" id="line1" placeholder="line1"><br>
<label for="line2">Enter your text: </label>
<input type="text" autocomplete="off" id="line1" placeholder="line2"><br>
<label for="line3">Enter your text: </label>
<input type="text" autocomplete="off" id="line1" placeholder="line3"><br>
//Click the "click-me' button to return the text on the "HTML" button
<button onclick="myFunction()">Click me</button>
</form>
</div>
Try this. For the button, the element being displayed only stays if the user keep on holding the button. Thus I changed it to a radio box where you can style it into a button.
The button has been linked with the canva and the inserted in the different textbox are being displayed respectively.
Edit: I have added a reset code to reset the canva and also styled the two "buttons".
Tested and works
<canvas id="myCanvas" width="900" height="600" style="border:1px solid #404040;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
function myFunction() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var img =new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0, 900, 600);
}
//the code below positions the overlaying text on the image
ctx.font = "bold 36px Times";
ctx.fillStyle = "black";
ctx.fillText ( document.getElementById("line1").value ,400,325);
ctx.fillText ( document.getElementById("line2").value ,400,375);
ctx.fillText ( document.getElementById("line3").value ,400,425);
}
img.src= "images/image1.jpg"
function myFunction2() {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
}
//this is the image
</script>
//the code below allows the user to input text into boxes
<div>
<form>
<label for="line1">Enter your text: </label>
<input type="text" autocomplete="off" id="line1" placeholder="line1"><br>
<label for="line2">Enter your text: </label>
<input type="text" autocomplete="off" id="line2" placeholder="line2"><br>
<label for="line3">Enter your text: </label>
<input type="text" autocomplete="off" id="line3" placeholder="line3"><br>
//Click the "click-me' button to return the text on the "HTML" button
<a id="input-button" onclick="myFunction()">Click me</a>
Reset
</form>
</div>
<style>
#input-button {
padding: 2em;
background-color: black;
color: #fff;
}
#input-reset {
padding: 2em;
background-color: black;
color: #fff;
text-decoration: none;
}
</style>

Rotation using cropper js

I'm working with the croppers library, I have the problems implementing it on some Android devices the photo being taken vertically I get horizontal I tried to adapt the horizontal or vertical rotation part (90 or 180 degrees) with copper js but not Succeeded at all.
video
I'm working my code in meteor I leave a part of the code.
html part
<div class=" col-xs-6 ">
<div>
{{#if photo_2}}
<img class="img-responsive" src='{{photo_2}}' alt="" style="width:1531px;height:114px;"/>
{{else}}
<img class="img-responsive" src="/persona2.png" alt="" />
{{/if}}
</div>
<div class="col-xs-12">
<button type="" class="btn-default btn-picture btn" id="btn2"><i class="fa fa-plus plus" aria-hidden="true"></i></button>
</div>
</div>
<input type="hidden" id="photoid">
<input id="file-upload" style="display: none;" type="file" accept="image/*" />
<div id="snackbar">
<img class="img-responsive cameraphoto" id="cameraphoto" src="/camera-icon-55.png" alt="" />
<img class="img-responsive" id="explorer" onclick="$('#file-upload').click();" src="/camera-icon-56.png" alt="" />
<img class="img-responsive" id="delete" src="/delete.png" />
</div>
<div id="crops" style="display: none; background-color: black;height: 100vh;">
<canvas id="canvas" height="5" width="5" style="display: none;"></canvas>
<img id="target" style="max-width: 100%" />
<img id="targeted" style="max-width: 100%" />
<div style="position: absolute; margin-top: 145px; bottom: 20px; width: 100%;text-align: center;">
<center>
<img class="img-responsive" id="Save" src="/save.png" alt="" style="width: 48px;margin-left: -78px;"/>
<img class="img-responsive" id="cancel" src="/cancel.png" alt="" style="width: 54px;margin-left: 62px;margin-top: -50px;"/>
<image id="Browser" src=""/>
</center>
<input type="hidden" id="photoid">
</div>
<input type="hidden" name="imgX1" id="imgX1" />
<input type="hidden" name="imgY1" id="imgY1" />
<input type="hidden" name="imgWidth" id="imgWidth" />
<input type="hidden" name="imgHeight" id="imgHeight" />
<input type="hidden" name="imgrotate" id="imgrotate" />
<input type="hidden" name="imgscaleX" id="imgscaleX" />
<input type="hidden" name="imgscaleY" id="imgscaleY" />
</div>
javaScript code
'click .cameraphoto' : function(e , instance) {
var photoid = $('#photoid').val();
var options = {
width: 800,
height: 600,
};
MeteorCamera.getPicture(options, function (error, data) {
if (!error) {
$('#photos').hide();
$('#crops').show();
document.getElementById('target').src = "";
document.getElementById('target').src = data;
$('#target').cropper( {
aspectRatio: 1 / 1,
minCropBoxWidth : 150,
minCropBoxHeight :150,
crop: function(e) {
$('#imgX1').val(e.x);
$('#imgY1').val(e.y);
$('#imgWidth').val(e.width);
$('#imgHeight').val(e.height);
$('#imgrotate').val(e.rotate);
$('#imgscaleX').val(e.scaleX);
$('#imgscaleY').val(e.scaleY);
}
// cropper.rotate(instance.state.get("left"));
// rotateTo(instance.state.get("left"))
});
}
});
}
'change #file-upload' :function(e) {
$(".loader").fadeIn("slow");
encodeImageFileAsURL();
function encodeImageFileAsURL(){
var filesSelected = document.getElementById("file-upload").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
$('#photos').hide();
$('#crops').show();
$(".loader").fadeOut("slow");
document.getElementById('target').src = "";
document.getElementById('target').src = fileLoadedEvent.target.result;
$('#target').cropper( {
aspectRatio: 1 / 1,
minCropBoxWidth : 150,
minCropBoxHeight :150,
crop: function(e) {
$('#imgX1').val(e.x);
$('#imgY1').val(e.y);
$('#imgWidth').val(e.width);
$('#imgHeight').val(e.height);
$('#imgrotate').val(e.rotate);
$('#imgscaleX').val(e.scaleX);
$('#imgscaleY').val(e.scaleY);
}
});
}
fileReader.readAsDataURL(fileToLoad);}}
},
'click #Save' : function(e) {
$(".loader").fadeIn("slow");
e.preventDefault();
var photoid = $('#photoid').val();
var x1 = $('#imgX1').val();
var y1 = $('#imgY1').val();
var width = $('#imgWidth').val();
var height = $('#imgHeight').val();
var rotate = $('#imgrotate').val();
var scaleX = $('#imgscaleX').val();
var scaleY = $('#imgscaleY').val();
var canvas = $("#canvas")[0];
var context = canvas.getContext('2d');
var img = new Image();
img.src = $('#target').attr("src");
img.onload = function () {
canvas.height = height;
canvas.width = width;
context.drawImage(img, x1, y1, width, height, 0, 0, width, height);
var dataURL = canvas.toDataURL("image/jpeg");
//console.log('canvas',dataURL);
var photo = {
srcData : dataURL,
userid : Meteor.userId(),
photo_id : photoid
}
Meteor.call('updatePhoto',photo,function(err) {
if (!err) {
$('#photos').show();
$('#crops').hide();
$('#imgX1').val('');
$('#imgY1').val('');
$('#imgWidth').val('');
$('#imgHeight').val('');
$('#imgrotate').val('');
$('#imgscaleX').val('');
$('#imgscaleY').val('');
canvas.height = 0;
canvas.width = 0;
//page relod is better than
FlowRouter.go('/search');
FlowRouter.go('/addphoto');
}
});
}
},
'click #cancel' :function() {
$('#photos').show();
$('#crops').hide();
document.getElementById('target').src="";
FlowRouter.go('/search');
FlowRouter.go('/addphoto');
},
My solution was based on the following
'click #rotateL': function(e, instance){
$('#target').cropper('rotate', -90);
},
'click #rotateR': function(e, instance){
$('#target').cropper('rotate', 90);
},
'click #Save' : function(e) {
$(".loader").fadeIn("slow");
e.preventDefault();
var photoid = $('#photoid').val();
var canvas = $('#target').cropper('getCroppedCanvas');
console.log(canvas)
var dataURL = canvas.toDataURL("image/jpeg");
var photo = {
srcData : dataURL,
userid : Meteor.userId(),
photo_id : photoid
}
Meteor.call('updatePhoto',photo,function(err) {
if (!err) {
$('#photos').show();
$('#crops').hide();
canvas.height = 0;
canvas.width = 0;
//page relod is better than
//document.getElementById('target').src="";
FlowRouter.go('/search');
FlowRouter.go('/addphoto');
}
});
},

Can I insert an image on the input file one by one in one submit

When I insert images one by one, the 'input file' only reads one picture only.
But when I insert images in multiple, the result is read as much as the image that the user inputs
window.onload = function() {
//Check File API support
if (window.File && window.FileList && window.FileReader) {
var filesInput = document.getElementById("files");
filesInput.addEventListener("change", function(event) {
var files = event.target.files; //FileList object
var output = document.getElementById("result");
for (var i = 0; i < files.length; i++) {
var file = files[i];
//Only pics
if (!file.type.match('image'))
continue;
var picReader = new FileReader();
picReader.addEventListener("load", function(event) {
var picFile = event.target;
var div = document.createElement("div");
div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
"title='" + picFile.name + "'/>";
output.insertBefore(div, null);
});
//Read the image
picReader.readAsDataURL(file);
}
});
} else {
console.log("Your browser does not support File API");
}
}
article {
width: 80%;
margin: auto;
margin-top: 10px;
}
.thumbnail {
height: 100px;
margin: 10px;
}
<article>
<label for="files">Select multiple files: </label>
<input id="files" type="file" multiple/>
<div id="result"></div>
</article>
Please do multiple image input, and one by one
If you want to upload a photo multiple.
This method will prevent, where the user has entered one picture, then, the user will be able to enter the next picture before uploading
$(document).ready(function() {
$(document).on("click", 'input[name="images-post[]"]', function() {
$('.menu-create-post .mdi-camera').append('<input type="file" name="images-post[]" accept="image/*" multiple="multiple">');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="wrapper">
<span class="span-wrapper" style="display: inline-block;">
<input type="file" name="images-post[]"/>
</span>
</div>
<div class="menu-create-post">
<div class="mdi-camera"></div>
</div>

Upload many file on client side and compress it then upload compress file on server

I want to implement the concept site visitor can upload multiple files click on submit then compress files are upload on server xampp. I am using PHP scripting language.
You can do this in HTML5 supported browser with the help of Canvas API [for images only]. Here is a good example
http://makeitsolutions.com/labs/jic/
HTML5 canvas refrences:
http://diveintohtml5.info/canvas.html
http://www.html5canvastutorials.com/
Below is dummy code:
HTML [Check jQuery path]
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<style type="text/css">
.img_button{ height: 100%; width:100%}
.img_submit{ border: 1px saddlebrown solid; height: 30px; margin-top: 100px}
.box{ float: left; margin: 10px; width: 20%; height: 250px}
.label{ float: left; background: #333; color: #fff; width: 100%; padding-left: 10px }
img{float:left;}
</style>
</head>
<body>
<div class="box" id="box1">
<input class="filename" type="file" id="1" style="display:none" />
<input class="img_button" id="btn1" type="button" onclick="$('#1').trigger('click'); return false;" value="Image-1" />
</div>
<div class="box" id="box2">
<input class="filename" type="file" id="2" style="display:none" />
<input class="img_button" id="btn2" type="button" onclick="$('#2').trigger('click'); return false;" value="Image-2" />
</div>
<div class="box" id="box3">
<input class="filename" type="file" id="3" style="display:none" />
<input class="img_button" id="btn3" type="button" onclick="$('#3').trigger('click'); return false;" value="Image-3" />
</div>
<input class="img_submit" type="button" value="Upload" onclick="uploadFile();" />
<script type="text/javascript">
var imgCount = 1;
$('.filename').change(function(){
var file = this.files[0];
var id = this.id;
var reader = new FileReader();
reader.onload = function(event) {
var i = document.createElement('img');
i.src = event.target.result;
i.id = 'img'+id;
i.onload = function(){
image_width=$(i).width(),
image_height=$(i).height();
if(image_width > image_height){
i.style.width="320px";
}else{
i.style.height="300px";
}
//i.style.display = "block";
}
$('#img'+id).remove();
$('#box'+id).append(i);
$('#box'+id).prepend('<span class="label">'+$('#btn'+id).val()+'</span>');
$('#btn'+id).hide();
$(document).on('click', '#img'+id, function(){$('#'+id).trigger('click')});
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsDataURL(file);
});
function uploadFile(){
var img_data = [];
if(imgCount){
var quality = 0.3;
for(var i=1; i<=3; i++){
if(document.getElementById('img'+i)){
var source_img_obj = document.getElementById('img'+i);
var cvs = document.createElement('canvas');
cvs.width = source_img_obj.naturalWidth;
cvs.height = source_img_obj.naturalHeight;
var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);
var newImageData = cvs.toDataURL("image/jpeg", quality);
var img_name = $('#btn'+i).val();
img_data.push({index:i, name: img_name, image_data :newImageData});
}
}
var xhr = $.ajax({
url: 'a.php',
type: 'POST',
data: {post_data:img_data},
dataType: 'json'
});
xhr.success(function(response){
console.log(response);
});
}
}
</script>
</body>
</html>
PHP
<?php
$arr = $_POST;
if(isset($arr) && isset($arr['post_data'])){
$arrImageData = $arr['post_data'];
if(is_array($arrImageData)){
for($i=0; $i<count($arrImageData); $i++){
if($arrImageData[$i]['image_data'] != ''){
$varImageData = preg_replace('/^data:image\/(png|jpg|jpeg);base64,/', '', $arrImageData[$i]['image_data']);
$varImageData = base64_decode($varImageData);
$varImageIndex = $arrImageData[$i]['index'];
$varImageName = preg_replace('/[^a-zA-Z0-9]/', '-', $arrImageData[$i]['name']);
$varFileName = $varImageName.'-'.$varImageIndex.'.jpg';
$file = fopen($varFileName, 'wb');
fwrite($file, $varImageData);
fclose($file);
}
}
}
}
Client-side compression (before upload) can only be done via a Java Applet, as far as I know.
Server-side compression (after upload) can be done via PHP ZipArchive class. An example can be found here.
EDIT: In addition to Java Applets, client-side file compression can also be implemented in Flash or Silverlight, but if I understand correctly, this will compress data per file for quicker sending and not create a file archive.

Categories

Resources