Display image from a given url - javascript

I have an array with 3 cells.At the first cell i have a textarea where you can insert the url of an image.At the second cell i have a button which when you click the image display at the third cell where i have a div to display the image.The question is how can i display the image either from the internet either from local?
The code i wrote is:
function loadImage(){
var mydiv = document.getElementById("idofdivtodisplayimg");
var url = document.getElementById("idoftextareawhereyouputtheurl");
mydiv.innerHTML = url.value;
}

<html>
<body>
<input type="text" id="imagename" value="" />
<input type="button" id="btn" value="GO" />
<script type="text/javascript">
document.getElementById('btn').onclick = function() {
img = document.createElement('img');
img.src = document.getElementById('imagename').value;
document.body.appendChild(img);
}
</script>
</body>
</html>

You can see the sample code will add the images from an array to the document.
You could also append the images to any of the elements in your function by using url.appendChild
var arr = ['http://via.placeholder.com/350x150', 'http://via.placeholder.com/350x250','http://via.placeholder.com/350x350']; // hold image urls in an array.
arr.forEach(function(item){
// loop through array and add images to the document.
var img = new Image();
img.src = item;
document.body.appendChild(img);
});

In order to do both you would need to change your html and code.
For the case when the user has a url you can just create a new image and append it to your div setting the image's src to the url that was set in the input:
function loadImage(){
var mydiv = document.getElementById("idofdivtodisplayimg");
var url = document.getElementById("idoftextareawhereyouputtheurl");
var image = new Image;
mydiv.appendChild(image);
image.src = url.value;
}
Now to get it to display a local image you will need a file input or a drag and drop scheme as you cannot access local files without some type of user interaction.
So you would, for example, need to change your html to include a file input, and grab a reference to the selected file the user selects. Then use FileReader to read the file, and finally display it
HTML
<input type="file" id="imagefile">
JS
//input reference
var imageinput = document.getElementById("imagefile");
imageinput.addEventListener('change',function (){
var mydiv = document.getElementById("idofdivtodisplayimg");
var image = new Image;
mydiv.appendChild(image);
//FileReader instance
var reader = new FileReader;
reader.addEventListener('load',function(){
//reader.result will contain a dataURL that can be used
//like a regular image url
image.src = reader.result;
});
//read the file as a dataURL
reader.readAsDataURL( imageinput.files[0] );
});

This does both, it let's you upload an image (or at least load it to the browser) or give a URL to an image source. Click the button and the image is loaded and displayed!
This snippet uses the FileReader API to get the uploaded image and display it in an image element
function uploadOrNot() {
if (document.querySelector("input[type=file]").files[0]){
let input = document.querySelector("input[type=file]");
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
display(e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
} else if (document.querySelector("input[type=text]").value){
display(document.querySelector("input[type=text]").value);
}
}
function display(res) {
let img = document.createElement("IMG");
img.src=res;
document.querySelector("#result").appendChild(img);
}
<div id="urlOrUpload">
<input type="text"/>
<br>
<input type="file" accetp="image/*"/>
</div>
<div id="buttonHolder">
<button type="button" onclick="uploadOrNot()">Display</button>
</div>
<div id="result"></div>

I partly solved it by replacing the div at the third cell with an img tag and at the function i wrote above, i chenged it to:
var image = document.getElementbyId("imageid");
var url = document.getElementbyId("urlid");
image.src = url.value;
But at the table i have,i also have a button where you can add a same row as above.How can i do this function for every url that is placed at every textbox?

Related

Show local image file on the web

I'm developing a website to recommend clothes. So, I want customers to put their image which is in their local.
First, I tried <input type='file' accept='image/*' ~~>. But it doesn't provide customizing option. I must show the button with my picture.
Therefore I tried button option and write the code like this.
function openImageFile() {
var input = document.createElement("input");
input.type = "file";
input.accept = "image/*";
input.click();
input.onchange = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function() {
var dataurl = reader.result;
var output = document.getElementById('output');
output.src = dataURL;
output.width = 125;
output.height = 125;
};
photo = input.files[0];
reader.readAsDataURL(input.files[0]);
}
}
<button type="button" id="test" onclick="openImageFile()"><img src="blah.png"></button>
<img id='output'>`
Convert your image to data protocol.
Converter: https://base64.guru/converter/encode/image
Set the src of your image element to:
<image src="data:image/png;base64,OUPUT_FROM_ENCODER" />
This allows your website to load a image without it being hosted by a URL

Save <img> to File Share using AJAX

I am trying to somehow save my image generated with <input type="file" id="file_capture" capture="user" accept="image/*"/> through vb.net ajax and save the file into a file share folder.
I need image capture so that if the user is on their phone it will screen capture.
I have tried jquery-webcame with no luck and have ended with only HTML Capture working up to the point when I need to save the file.
So far the image src looks something like this data:image/jpeg;base64,/...
When I pass the src into ajax I tried to read it using Net.WebClient but I am unsure how to get the address of the img when all I have is the src value to use for My.Computer.Network.DownloadFile
VB.NET
<System.Web.Services.WebMethod(EnableSession:=True)> Public Shared Function SaveImage(ByVal src As String) As String
Try
Dim client As Net.WebClient = New Net.WebClient
Dim destination = "\\serverName\FolderShareName\"
client.DownloadFile(src, destination)
Catch ex As Exception
End Try
Return "Pass"
End Function
HTML
<label class="cameraButton" style="min-width:150px;">Capture File
<input type="file" id="file_capture" capture="user" accept="image/*"/>
</label>
<div id="imageHolder" class="col-sm-12" style="border:1px solid red;text-align:center;min-width:150px;" runat="server">
</div>
JAVASCIRPT [I created it this way so multiple images can be uploaded]
$('#file_capture').change(function () {
AddNewImage(this);
});
function AddNewImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
var id = $("#imageHolder > div > img").length
var fullid = "uploadImage" + id++;
var DIV = document.createElement("DIV");
DIV.className = "imgWrap"
DIV.ID = "imgWrapID" + id++;
DIV.style.display = "inline-block";
DIV.style.padding = "10px";
document.getElementById('imageHolder').appendChild(DIV);
var img = new Image(200, 200);
reader.onload = function (e) {
img.src = e.target.result;
img.id = fullid
}
reader.readAsDataURL(input.files[0]);
var btn = document.createElement("BUTTON");
btn.innerHTML = "x";
btn.className = 'top-right';
btn.name = DIV.ID
btn.title = fullid
btn.onclick = function () {
$("#" + this.name).remove();
$("#" + this.title).remove();
$(this).remove();
return false;
};
DIV.appendChild(btn);
DIV.appendChild(img);
}
}
client.DownloadFile(src, destination)
clearly won't accept the 64bit src value of the image so I need to somehow convert it to a address.

compressing and saving image captured to localStorage

I'm working on an HTML widget which will be embedded in an iBook in iBooks Author for the iPad.
I've got a simple button to trigger image capture on an iPad and all is working fine.
<div id="zeroDiv">
<input type="file" id="getPic" accept="image/*">
</div>
<div id="picWrapper">
<img id="image">
<div id="buttDiv">
<button id="picButt"><span class="buttText">Insert image</span>
</button>
</div>
</div>
and
$('#picButt').click(function () {
$('#getPic').trigger('click');
});
$(document).ready(function () {
$("#getPic").on("change", gotPic);
$("#image").load();
});
function gotPic(event) {
$("#image").attr("src", URL.createObjectURL(event.target.files[0]));
$("#picButt span").text("Change image");
}
fiddle at https://jsfiddle.net/mikawaben/cq2yrh2z/
However, when the user moves off a page and returns, the image is lost as the page reloads. I need to store the image in localStorage.
I know that the fiddle at http://jsfiddle.net/VXdkC/2/ (courtesy of Musa on this site) holds code which could be the key for me.
$('#addNote').click(function () {
var Title = $('#title').val();
var Message = $('#message').val();
var pic = document.getElementById("file").files[0];
var imgUrl;
var reader = new FileReader();
reader.onload = function(e) {
var imgURL = reader.result;
$('#notes').prepend("<div class='entry'><h1>" + Title + "</h1></p>"+ "<p>" + Message + "<img src=" + imgURL + "></p> </div>");
var notes = $('#notes').html();
localStorage.setItem('notes', notes);
saveDataToLocalStorage(imgURL);
}
reader.readAsDataURL(pic);
return false;
});
//show content of notes in storage
$('#notes').html(localStorage.getItem('notes'));
return false;
But despite messing around with it for a couple of hours, I'm not getting it to work. Can anyone lend a hand with this?
I'm also concerned about compression. Do I need to use base64 encoding or something in case the image size causes the whole thing to crash?
Just check to see if there is an imaged saved on page load and display it. Then save the image when selected.
$(document).ready(function () {
$("#getPic").on("change", gotPic);
if (localStorage['url']){
$("#image").attr("src", localStorage['url']);
$("#picButt span").text("Change image");
}
});
function gotPic(event) {
var reader = new FileReader();
reader.onload = function(){
$("#image").attr("src", this.result);
localStorage['url'] = this.result;
$("#picButt span").text("Change image");
}
reader.readAsDataURL(event.target.files[0]);
}
https://jsfiddle.net/cq2yrh2z/1/

get width of uploaded image (before uploading file to server)

I have some code that i changed. It was prevusly to get file ext. I wannted it to get width of uploded image( before even clicking submit input ) and if it's too small giving alert. Problem is that i dont really know how i can connect this js code with html form.
<form id="add" method="POST" enctype="multipart/form-data" action="upload.php">
<input type="file" id= "filput" style="margin-bottom:30px; margin-top:20px;" name="file" size="40" />
</form>
$("#filput").on('change', function () {
var w = $(this).width();
if (w < 500) {
alert("too small");
} else {
alert("big");
}
});
The this referrs to the input not the image. You have too use the HTML5 file API.
You can use this example: How to get the image width from html 5 file API
Code example: copied from: Getting Image Dimensions using Javascript File API
$("#filput").on('change', function () {
var fr = new FileReader;
fr.onload = function() { // file is loaded
var img = new Image;
img.onload = function() {
alert(img.width); // image is loaded; sizes are available
};
img.src = fr.result; // is the data URL because called with readAsDataURL
};
fr.readAsDataURL(this.files[0]); // I'm using a <input type="file"> for demonstrating
});

Javascript Image Preview for page with lots of forms

I have a bunch of forms on a page that allow a user to edit information for each respective form. One of the inputs for the form is an image upload.
The forms are of the form below:
<form class="myForm" ...>
<div class="imagePreview"></div>
<input type="file" name="myImage" onchange="handleFiles(this.files)" />
</form>
And I have javascript to handle the image preview as follows:
function handleFiles(files) {
$(".obj").remove();
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var pic_div = document.getElementById("imagePreview");
var img = document.createElement("img");
img.classList.add("obj");
img.file = file;
pic_div.appendChild(img);
var reader = new FileReader();
reader.onload = (
function(aImg) {
return function(e) {
aImg.src = e.target.result;
};
}
)(img);
reader.readAsDataURL(file);
}
}
I want to replace the line:
var pic_div = document.getElementById("imagePreview");
with the appropriate line. This is where I am getting confused. I don't know how to refer to the div of class "imagePreview" for THIS FORM of class myForm.
Any help is much appreciated.
The problem is that you're getting the div with the Id imagePreview, when the div in the form have the imagePreview CSS class, what you can do is either give the div the required id, more less like this:
<div id="imagePreview"></div>
Or, if you will have multiple divs with the same class get them using jQuery like this:
$(".imagePreview").each(function(index){
//Do Something
});
Or:
var pic_div = $(".imagePreview")[0]

Categories

Resources