I'm trying to write a file upload script for use in a secure corporate intranet and having just a little trouble...
In the following code, I get no errors and all my debugging looks like everything is working, but the end result is always a 'blank' image:
var ctx = document.createElement('canvas');
var img = new Image();
img.onload = function(){
ctx.drawImage(img,0,0);
}
img.src = $('#UpdateImage:file');
var imgStr = ctx.toDataURL("image/png", "");
document.getElementById("Item_Create_Image_Avatar").src = imgStr;
When I "inspect element" on the 'Item_Create_Image_Avatar' object, the 'src' value looks absolutely perfect:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAEYklEQVR4Xu3UAQkAAAwCwdm/9HI83BLIOdw5AgQIRAQWySkmAQIEzmB5AgIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlACBB1YxAJfjJb2jAAAAAElFTkSuQmCC" id="Item_Create_Image_Avatar" style="vertical-align:top">
Why is my image coming in as blank?
Found This.
Select a File to Load:
<input id="inputFileToLoad" type="file" onchange="loadImageFileAsURL();" />
<div id="imgTest"></div>
<script type='text/javascript'>
function loadImageFileAsURL(){
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0){
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var divTest = document.getElementById("imgTest");
var newImage = document.createElement('img');
newImage.src = srcData;
divTest.innerHTML = newImage.outerHTML;
}
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
EDIT:
Source: How to convert image into base64 string using javascript
If you want to get the Data URL of the image after it loaded, you should get the Data URL after it loaded
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
imgStr = canvas.toDataURL("image/png", "");
document.getElementById("Item_Create_Image_Avatar").src = imgStr;
}
img.src = $('#UpdateImage:file');
EDIT: Included the rest of the code
EDIT2: Edited stupid error regarding canvas and its context
Related
I have found some answers related to the topic from How can I convert an image into Base64 string using JavaScript?. I realized they don't have an image on the div tag. Is it possible if I would have the image source?
Answer added for people who want to reference
function encodeImageFileAsURL() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("output").src = newImage.src;
alert("Converted Base64 version is " + document.getElementById("output").src);
console.log("Converted Base64 version is " + document.getElementById("output").src);
}
fileReader.readAsDataURL(fileToLoad);
}
}
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<img src="https://mdbootstrap.com/img/Photos/Others/placeholder-avatar.jpg" id="output" width="100" height="100" style="border-radius: 50%;" />
I would like to use the image source to load the image and find out the base 64. Is it possible?
Besides using div to create 1 image out where it can't be customized.
I think you want to do this https://jsfiddle.net/samet19/yv9a4op8/
function encodeImageFileAsURL() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("output").src = newImage.src;
}
fileReader.readAsDataURL(fileToLoad);
}
}
I am trying to add an image to the html page with just javascript and I have to do it without using innerHTML. I can't seem to get the images to appear at all.
javascript
var galleryPhotos = ["gallery/galleryphoto0.jpg", "gallery/galleryphoto1.jpg", "gallery/galleryphoto2.jpg", "gallery/galleryphoto3.jpg", "gallery/galleryphoto4.jpg"];
function newImage(){
var ele0 = document.createElement("img");
var image = document.getElementById("image");
ele0.scr = galleryPhotos[0];
image.appendChild(ele0);
var ele1 = document.createElement("img");
var image = document.getElementById("image");
ele1.scr = galleryPhotos[1];
image.appendChild(ele1);
var ele2 = document.createElement("img");
var image = document.getElementById("image");
ele2.scr = galleryPhotos[2];
image.appendChild(ele2);
var ele3 = document.createElement("img");
var image = document.getElementById("image");
ele3.scr = galleryPhotos[3];
image.appendChild(ele3);
var ele4 = document.createElement("img");
var image = document.getElementById("image");
ele4.scr = galleryPhotos[4];
image.appendChild(ele4);
}
What I am trying to put it into in html
<div id="image"></div>
Using chromes debugging tool doesn't help me at all.
You have a typo: scr should be src.
Try this:
var galleryPhotos = ["gallery/galleryphoto0.jpg", "gallery/galleryphoto1.jpg", "gallery/galleryphoto2.jpg", "gallery/galleryphoto3.jpg", "gallery/galleryphoto4.jpg"];
function newImage(){
var image = document.getElementById("image");
var i = 0;
while(galleryPhotos[i]){
el = document.createElement("img");
el.src = galleryPhotos[i];
image.appendChild(el);
i++;
}
}
I'm new to JavaScript and I made this code. The purpose of this code is to use JavaScript and HTML to display an ARRAY of images in a website. They all need to be displayed at once. This is the code so far, however it is not working.
<html>
<head>
<script>
var ArrayOfImages = [];
var Image1 = new Image1()
image1.src = "image1.jpg";
var Image2 = new Image2()
Image2.src = "image2.jpg";
var Image2 = new Image3()
Image3.src = "image3.jpg";
ArrayOfImages.push(Image1);
ArrayOfImages.push(Image2);
ArrayOfImages.push(Image3);
ArrayOfImages.toString();
document.write(ArrayOfImages);
</script>
</head>
<body>
</body>
</html>
When I run this code all I get is an empty webpage.
For anyone wondering, the images are in the same file as the html file. I'm also relatively new to JavaScript and HTML so please be clear in how to fix it.
You have to use array.forEach then append each array item in body.Like this
var ArrayOfImages = ['image1.jpg', 'image2.jpg', 'image3.jpg']; //your assumed array
ArrayOfImages.forEach(function(image) { // for each link l in ArrayOfImages
var img = document.createElement('img'); // create an img element
img.src = image; // set its src to the link l
document.body.appendChild(img); // append it to the body
});
See Fiddle: Fiddle
UPDATE
You can also set height and width as your requirement.Like below.
var ArrayOfImages = ['https://upload.wikimedia.org/wikipedia/commons/f/f9/Wiktionary_small.svg', 'https://upload.wikimedia.org/wikipedia/commons/f/f9/Wiktionary_small.svg', 'https://upload.wikimedia.org/wikipedia/commons/f/f9/Wiktionary_small.svg']; //your assumed array
ArrayOfImages.forEach(function(image) {
var img = document.createElement('img');
img.src = image;
img.height = "45";
img.width = "50";
document.body.appendChild(img);
});
The following code should be able to save and load .png image to/from local hard drive.
Saving works fine(at least in chrome) but loading produces wrong url and display nothing..
A little help would be really appreciated!
<html>
<head>
<title></title>
</head>
<body>
<img id="img" /><br>
<input type="button" value="Save" onclick="onSave()" /><br />
<input type="file" onchange="onOpen(event)" /><br />
<script>
onSave = function () {
var canvas = document.createElement("canvas");
canvas.width = 200;
canvas.height = 200;
var ctx = canvas.getContext("2d");
ctx.fillRect(0, 0, 100, 150);
var dataURL = canvas.toDataURL("image/png");
var img64 = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
var binaryImg = atob(img64);
var length = binaryImg.length;
var ab = new ArrayBuffer(length);
var ua = new Uint8Array(ab);
for (var i = 0; i < length; i++) {
ua[i] = binaryImg.charCodeAt(i);
}
var blob = new Blob([ab]);
var a = document.createElement("a");
a.download = 'Blob_img';
a.innerHTML = "Download File";
a.href = window.webkitURL.createObjectURL(blob);
a.style.display = 'none';
document.body.appendChild(a);
a.click();
};
onOpen = function (event) {
var fileReader = new FileReader();
fileReader.onload = function (event) {
var ab = event.target.result;
var ua = new Uint8Array(ab);
var binaryImg;
for (var i = 0; i < ua.length; i++) {
binaryImg += String.fromCharCode(ua[i]);
}
var img64 = btoa(binaryImg);
var image = new Image();
image.src = 'data:image/png;base64,' + img64;
var img = document.getElementById('img');
img.src = image.src;
}
fileReader.readAsArrayBuffer(event.target.files[0]);
};
</script>
</body>
</html>
Your "load" handler for your FileReader is declared without an event parameter. As a result, it's not going to have access to the file contents.
fileReader.onload = function (event) {
var ab = event.target.result;
Without that parameter, the symbol "event" would refer to the parameter of the enclosing function, and that one won't have the file contents.
Also, I think you don't need to do the base64 encoding/decoding via atob and btoa, because the results of converting the canvas contents to a data URL will be a base64 string anyway.
In case somebody is wondering, there is a simpler way of reading the file:
FileReader.readAsDataURL
Check a working example at https://developer.mozilla.org/en-US/docs/Web/API/FileReader.readAsDataURL.
I'm currently following this tutorial for uploading images to Google Drive from javascript. The example code works perfectly in that you can select a file to upload from your hard drive. I'm now trying to modify it for my purposes so that it instead uploads an image already displayed on the page in standard HTML form:
<img class="image" id="result-image" src="imgres?img_id={{result_id}}" alt="No Image"/>
The supplied Google example looks for a change on the file selector and gets the file data as follows:
var fileData = evt.target.files[0];
Which is then read by a FileReader object as follows:
var reader = new FileReader();
reader.readAsBinaryString(fileData);
reader.onload = function(e) {
...
My question is how do I supply the image object tag in the required type for the FileReader readAsBinaryString method so that the Drive API calls can succeed? Thanks in advance!
Fixed using Joe Coder's solution as follows:
var img = document.getElementById('result-image');
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
var dataUrl = canvas.toDataURL('image/png');
var blob = dataUriToBlob(dataUrl);
var reader = new FileReader();
reader.readAsBinaryString(blob);
reader.onload = function(e) {
...
With dataUriToBlob method:
function dataUriToBlob(dataURI) {
// serialize the base64/URLEncoded data
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0) {
byteString = atob(dataURI.split(',')[1]);
}
else {
byteString = unescape(dataURI.split(',')[1]);
}
// parse the mime type
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// construct a Blob of the image data
var array = [];
for(var i = 0; i < byteString.length; i++) {
array.push(byteString.charCodeAt(i));
}
return new Blob(
[new Uint8Array(array)],
{type: mimeString}
);
}