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
Related
I am building a simple website where a user can upload multiple images and afterward click on a button to batch upload them to an AWS S3 bucket using PHP. Therefore the images need to be stored locally but also be accessible by PHP. So far I've learned that cookies are too small to store images and that the localstorage is not accessible using PHP.
This I what I've done so far:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<ul>
<li>
<h1 class="title" id="pages_count"></h1>
<div id="images" class="images"></div>
</li>
<br>
<li id="add_img_li">
<form runat="server">
<label class="custom-file-upload" id="add_img_btn">Add image
<input type="file" name="file" id="imgInp" accept="image/*">
</label>
</form>
<br>
</li>
<li>
<form action="includes/upload.inc.php" method="post" enctype="multipart/form-data">
<button class="custom-file-upload" id="uploadbtn" type="submit" onclick="btnChange()">Upload</button>
</form>
</li>
</ul>
</div>
<script>
// hide uploadbtn until image is uploaded
document.getElementById("uploadbtn").style.visibility = "hidden";
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
// function for converting images to base64
function getDataUrl(img) {
// Create canvas
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// Set width and height
canvas.width = img.width;
canvas.height = img.height;
// Draw the image
ctx.drawImage(img, 0, 0);
return canvas.toDataURL('image/jpeg');
}
// live image preview
var uploaded_img_count = 0;
var current_img = 0;
var imgs_left = 5;
function readURL(input) {
if (input.files && input.files[0]) {
if (uploaded_img_count < 5) {
// create image
console.log("image: " + uploaded_img_count.toString());
var image = document.createElement("li"); // Create a <button> element
image.innerHTML = '<img id="preview_' + uploaded_img_count.toString() +
'" src="#" alt="Scan" width="100" height="100" draggable="false" class="preview_img" style="visibility: visible;"/><br>'; // hidden
document.getElementById("images").appendChild(image); // Append <button> to <body>
var reader = new FileReader();
reader.onload = function (e) {
console.log("imageaaf<sdf: " + current_img.toString());
document.getElementById('preview_' + current_img.toString()).src = e.target.result
current_img++;
}
reader.readAsDataURL(input.files[0]); // convert to base64 string
// save image to cookie for batch upload
const img = document.querySelector("#preview_" + uploaded_img_count.toString());
img.addEventListener('load', function (event) {
const dataUrl = getDataUrl(event.currentTarget);
document.cookie = "img_" + uploaded_img_count.toString() + "=" + dataUrl +
";expires=Fri, 7 Jan 2022 12:00:00 UTC;path=/";
console.log(document.cookie);
});
uploaded_img_count++;
imgs_left--;
// update pages count label & remove add button if maximum image number is reached
if (uploaded_img_count >= 5) {
document.getElementById('add_img_li').parentNode.removeChild(document.getElementById('add_img_li'));
}
document.getElementById('pages_count').innerText = uploaded_img_count.toString() +
" / 5 pages uploaded";
// unhide findtasks button
document.getElementById("uploadbtn").style.visibility = "visible";
}
}
}
$("#imgInp").change(function () {
readURL(this);
});
</script>
The issue here is that when I try to log the cookies, it just says: img_1=data:image/jpeg; instead of showing me the base64 string. I'd like to save the images on the phone before uploading them for performance reasons. Previously I had to wait about 10 seconds after taking an image until I could capture another one. Are there any other ways to do this without cookies or localstorage?
Images on a user's local machine are never accessible to php as it runs on the server. You should look into creating an upload functionality using either HTML forms or JavaScript.
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 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?
We are working on a Email Encrypted Service. Here I have designed a html page (User Registration) where I have provided an area for uploading a file with extentions .crt, .cer and .der
This is HTML Content:
<section>
<label class="label">PubLic Key File</label>
<div>
<input type="file" id="fileInput">
</div>
<div id="fileDisplayArea"></div>
</section>
<button type="submit" class="button">Submit</button>
Javascript Code is:
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var imageType = /image.*/
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerHTML = "";
var img = new Image();
img.src = reader.result;
fileDisplayArea.appendChild(img);
}
reader.readAsDataURL(file);
} else {
fileDisplayArea.innerHTML = "File not supported!";
}
});
}
I have copied this Javascript Code (beginner in javascript) . It Only Accepts image file. I want to change this code which only accepts .crt, .cer and .der Extentions.
Thank you :)
Your current regex will actually match any filename that contains the word "image" (any part of the filename that is "image" followed by zero or more characters)
If you want to match filenames that end in ".crt", ".cer" or ".der", you can use this regex:
var imageType = /\.crt|cer|der$/
You can test regular expressions using Rubular
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]