I am trying to create a web-app which allows the user to upload an image from their pc, and from that, it will create an object, and add it into an array (to have record of it and its properties) and also display it on screen.
I have created a codepen: https://codepen.io/eve_mf/pen/XebVWv
html:
<form id="form" action="" method="post" enctype="multipart/form-data">
<div class="file-uploader-wrapper">
<input id="file-uploader" class="file-uploader-input" type='file' onchange="retrieveImageFromUpload(this);"/>
<button class="file-uploader-btn" type="button">Select an image</button>
</div>
</form>
<div id="map-view"></div>
js:
let allImages = [];
let displayImages = document.getElementById("map-view");
let imagesCounter = 0;
$(".file-uploader-btn").click(function() {
$("#file-uploader").click();
});
function retrieveImageFromUpload() {
let imgReader = new FileReader();
imgReader.readAsDataURL(document.getElementById("file-uploader").files[0]);
imgReader.onload = function (imgReaderEvent) {
let imageUploadedName = imgReaderEvent.target.result;
return readUploadedImage(imageUploadedName);
};
}
//create HTML image from the uploaded img
function readUploadedImage(imageUploadedName) {
imagesCounter++;
let img = document.createElement('img');
img = {
"id": 'screen-' + imagesCounter,
"src": imageUploadedName,
"alt": 'Default-alt'
};
allImages.push(img);
console.log(allImages);
var imgHTML = img.cloneNode(true);
imgHTML = "<img id='"+ img.id + "' src='" + img.src + "' alt ='" + img.alt + "' />";
displayImages.appendChild(imgHTML);
console.log("-------------");
}
My problem begins after creating the image element; I think I am getting confused but I can not really understand where or why.
I create an image with "let img = document.createElement('img');"
Then, I set its properties as object, and I think it is here where I get messed up. Then, I put this object into my array (called allImages), so, this is what I want so far.
But then, a part from adding this object into my array, I want to display it as an HTML image, I am trying this with "appendChild", But definitely is something really wrong because I get the error that I am not operating with a node element.
Can someone give me a push to the right path?
Thank you
Here I corrected your codepen.
You have to create a DOM element in order to add it to the page:
var imgHTML = document.createElement("IMG");
imgHTML.setAttribute("id", img.id);
imgHTML.setAttribute("src", img.src);
Tested and working.
You're redifining img as a regular object literal, loosing the image in the process.
You have to set the properties one by one
let img = document.createElement('img');
img.id = 'screen-' + imagesCounter;
img.src = imageUploadedName;
img.alt = 'Default-alt;
What you're doing is pretty much the same as
let x = 'image';
x = {id : 4};
console.log(x); // no suprise, it's just {id : 4} and the string was lost
It was a node element:
let img = document.createElement('img');
But then you got rid of the node element and replaced it with a custom object:
img = {
//...
};
This completely removed the node element, now all img has is your custom object with those three properties. Instead of creating a new object, just set the properties directly:
let img = document.createElement('img');
img.id = 'screen-' + imagesCounter;
img.src = imageUploadedName;
img.alt = 'Default-alt';
Related
I would like to add an image to a website using a javascript array. I found a code and then I tried to change it. But i can't get it to work. My code does not display the image on the site.
Code I found:
const imageOut = document.querySelector('.image-out');
for (let key in images) {
let img = document.createElement('img');
img.setAttribute('data-key', key);
img.src = 'images/' + key + '.png';
imageOut.append(img);
}
html tag: <div class="image-out"></div>
Array:
const images = {"JD-03-128" :{},"JD-05-128": {},"JD-07-128": {},"JD-11-128": {},"JD-12-128": {},"JD-13-128": {},"JD-15-128": {}};
My code:
var imageOut = document.querySelector(".image-out");
for (let key in a) {
let img = document.createElement('img');
img.setAttribute('data-key', key);
img.src = 'image/'+key+'.jpg';
imageOut.append(img);
}
html tag: <div class="image-out"></div>
Array:
const a = {"a":{},"b":{},"c":{},"d":{},"e":{},"f":{},"g":{}};
image my code: jpg, name absolutely match, name folder absolutely match with folder in my code.
where is my problem ?
If you want to append (add) multiple images to an HTML document using an array, then you can do something like below.
const rootElement = document.getElementById('root')
const array = [
'https://picsum.photos/id/237/200/300',
'https://picsum.photos/id/238/200/300',
'https://picsum.photos/id/239/200/300'
]
array.forEach((src) => {
const imageElement = document.createElement('img')
imageElement.src = src
rootElement.appendChild(imageElement)
})
img{margin:5px}
<div id='root'></div>
Explanation
So basically I'm creating an <img src='' /> element for every item in the array. The items in the array are the url (src) of the images. Those are added as an attribute to the imageElement like so imageElement.src = src and finally they are appended as a child of rootElement
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.
I am trying to create an image link based on the location of the server it is hosted on. If the server is server1. I want the image to be linked to http://server1/dod" I'm trying to get two images with this shot. However, nothing is loading. I am missing a piece and I don't know where. I'm also hosting this on an IIS server.
<!DOCTYPE html>
<html>
<body>
<div>
<p id="Images"></p>
</div>
<script>
var local = location.hostname;
//SP Edit, save a reference to the images node
var Images = document.getElementById("Images");
var dodlink = document.createElement(a);
dodlink.href = "http://" + local + "/DoD/";
var dodimg = document.createElement("img");
//SP Edit dodimg.src ="DOD.png";
//SP Edit dodimg.width = 256;
//SP Edit dodimg.height = 256;
dodimg.setAttribute("src", "DOD.png");
dodimg.setAttribute("width", "256px");
dodimg.setAttribute("height", "256px");
dodlink.appendChild(dodimg);
//SP Edit document.getElementByID("Images").innerHTML = dodimg;
Images.appendChild(dodimg);
var derlink = document.createElement(a);
//SP Edit derlink.href = "http://" + local + "/DER/";
deflink.setAttribute("href", "http://" + local + "/DER/");
var derimg = document.createElement("img");
//SP Edit derimg.src ="DER.png";
//SP Edit derimg.width = 256;
//SP Edit derimg.height = 256;
derimg.setAttribute("src", "DER.png");
derimg.setAttribute("width", "256px");
derimg.setAttribute("height", "256px");
deflink.appendChild(derimg);
//
Images.appendChild(deflink);
Try this:
var local = location.hostname;
var dodlink = document.createElement('a');
dodlink.href = "http://" + local + "/DoD/";
var dodimg = document.createElement("img");
dodimg.setAttribute("src", "DOD.png");
dodimg.setAttribute("width", "256");
dodimg.setAttribute("height", "256");
dodlink.appendChild(dodimg);
document.getElementById("Images").appendChild(dodlink);
var derlink = document.createElement('a');
derlink.href = "http://" + local + "/DER/";
var derimg = document.createElement("img");
derimg.setAttribute("src", "DER.png");
derimg.setAttribute("width", "256");
derimg.setAttribute("height", "256");
derlink.appendChild(derimg);
document.getElementById("Images").appendChild(derlink);
The image sizes are wrong. You need to specify the type eg
derimg.width = "256px";
instead of
derimg.width = 256;
also you are changing the
"innerHtml", which is wrong. You need to change the src of an IMG tag and then append it to the "innerHtml".
Also what value is 'a'? Since you've included a whole page I can't see 'a' defined.
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?
I have a message or string which contain both text as well as images as below.
var text = '<span class="user_message">hiiiiiii <img title=":benztip" src="path../files/stickers/1427956613.gif"> <img src="path../files/stickers/416397278.gif" title=":happy"></span>';
Before appending this to the the chat div i want to replace the src of the images to a default image.
How can i do that with Javascript or Jquery?
You can wrap your string into a jQuery-object and use the .find()-method to select the images inside the message-string:
var msg = '<span class="user_message">hiiiiiii<img title=":benztip" src="path../files/stickers/1427956613.gif" /><img src="path../files/stickers/416397278.gif" title=":happy" /></span>';
var $msg = $(msg);
$msg.find('img').attr('src', 'path_to_img');
$("#chat_content").append($msg);
Demo
Something like this in plain old JavaScript might work for you
// save string to temporary element
var tmp = document.createElement('div');
tmp.innerHTML = '<span class="user_message">hiiiiiii <img title=":benztip" src="path../files/stickers/1427956613.gif"> <img src="path../files/stickers/416397278.gif" title=":happy"></span>';
// loop through images
var imgs = tmp.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
var src = imgs[i].getAttribute("src"); // get current src
src = "http://placehold.it/100x100"; // do something with path
imgs[i].setAttribute("src", src); // set it
}
// output or whatever
document.writeln(tmp.innerHTML);
Try this for javascript solution, will work in older browsers too.
var spanNode = document.getElementById("spanId");
spanNode.getElementsByTagName("img")[0].src = "Src1";
spanNode.getElementsByTagName("img")[1].src = "Src2";
You can also use For loop for tagnames if there are more than 2 images.
document.getElementById("image_id").src="default_img_name";