Code work create a working base64 but when i try img.src = imgbase64
;
on a fly it not work, but if copy that base64 image and paste manually to src it work. IN CODE SNIPPET PRESS ON IMAGE AND UPLOAD ANY IMAGE
Question:
How to attache generated on fly image base64 string, to an html img element?
Steps:
- Click on any image
- Upload any image
- Then code convert you uploaded image to base64
- Error here, when adding base64 to src it's not working
function log(msg){return console.log(msg); } function removeClass(el, _className="active"){if(el){return hasClass(el, _className) ? el.classList.remove(_className) : true; } return false; } function hasClass(el, _className="active"){if(el.classList.contains(_className)){return true; } else {return false; } return false; } function getElement(target, targetFrom=false){return targetFrom ? targetFrom.querySelector(target) : document.querySelector(target); } function getElements(target, targetFrom=false){return targetFrom ? [...targetFrom.querySelectorAll(target)] : [...document.querySelectorAll(target)]; } function getElementById(target, targetFrom=false){return targetFrom ? targetFrom.getElementById(target) : document.getElementById(target); } function addClass(el, _className="active"){if(el){return !hasClass(el, _className) ? el.classList.add(_className) : true; } return false; } function getParent(el, idx){previouslyParent = el.parentElement; for (let index = 0; index < idx - 1; index ) {previouslyParent = previouslyParent.parentElement; } return previouslyParent; } function getOffset(el) {const rect = el.getBoundingClientRect(); return {"top": rect.top window.scrollY, "left": rect.left window.scrollX }; } function objectToTagStyles(selector, styles){if(styles){var style = document.createElement('style'); resonanceCssString = `${selector} {`; for (const [key, value] of Object.entries(styles)) {resonanceCssString = `${key}:${value};`; } resonanceCssString = "}"; if (style.styleSheet) {style.styleSheet.cssText = resonanceCssString; } else {style.appendChild(document.createTextNode(resonanceCssString)); } document.getElementsByTagName('head')[0].appendChild(style); return true; } return false; } function objectToCssTextStyles(styles){if(styles){resonanceCssString = ''; for (const [key, value] of Object.entries(styles)) {resonanceCssString = `${key}:${value};`; } return resonanceCssString; } return false; } function getAttribute(element, attr, isReturnValue){return isReturnValue ? element.attributes[attr].value : element.attributes[attr]; } function stringGen(yourNumber){var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < yourNumber; i ){text = possible.charAt(Math.floor(Math.random() * possible.length)); } return text; }
let base64String = "";
function imageUploaded() {
var file = this['files'][0];
var reader = new FileReader();
reader.onload = function () {
base64String = reader.result;
imageBase64Stringsep = base64String;
console.log(base64String);
}
imgToChange = getElement(`.change-this-image__${this.id}`);
imgToChange.src = base64String;
reader.readAsDataURL(file);
return base64String;
}
imgs = getElements('img');
svgs = getElements('svg');
getElement('body').style.position = 'relative';
for(let imageElement of imgs){
newChangeImageWrapper = document.createElement("label");
newChangeImageInput = document.createElement("input");
addClass(newChangeImageWrapper, 'reverb-image-changer');
randomNewWapperId = stringGen(10);
randomNewInputId = stringGen(10);
currentImgOffset = getOffset(imageElement);
addClass(newChangeImageWrapper, `reverb-image-changer--id_${randomNewWapperId}`);
newChangeImageWrapper.setAttribute("for", randomNewInputId);
newChangeImageInput.setAttribute("id", randomNewInputId);
newChangeImageInput.type = "file";
newChangeImageInput.onchange = imageUploaded;
newChangeImageWrapper.appendChild(newChangeImageInput)
addClass(imageElement, `change-this-image__${randomNewInputId}`);
currentImageBoundaries = imageElement.getBoundingClientRect();
currentWrapperStyles = {
"width": `${currentImageBoundaries.width}px`,
"height": `${currentImageBoundaries.height}px`,
"position": "fixed",
"top": `${currentImageBoundaries.y}px`,
"left": `${currentImageBoundaries.x}px`
}
newChangeImageWrapper.style.cssText = objectToCssTextStyles(currentWrapperStyles);
getElement('body').appendChild(newChangeImageWrapper);
}
.reverb-image-changer{
display: block;
border: 1px solid transparent;
text-align: center;
color: white;
cursor: pointer;
margin-top: 0;
transition: .3s;
z-index: 999;
}
.reverb-image-changer:hover{
border-color: rgb(46, 204, 113);
cursor: pointer;
}
.reverb-image-changer input{
width: 0px;
height: 0px;
visibility: hidden;
position: absolute;
top: 0;
left: -100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<img src="https://picsum.photos/200/300" alt="" width="200" height="300">
<img src="https://picsum.photos/200/300" alt="" width="200" height="300">
<img src="https://picsum.photos/200/300" alt="" width="200" height="300">
<img src="https://picsum.photos/200/300" alt="" width="200" height="300">
</body>
</html>
It looks like your post is mostly code; please add some more details.
CodePudding user response:
You need to wait until the image was loaded.
Better change the <img>
src within your onload
event callback:
function imageUploaded() {
var file = this["files"][0];
var currentID = this.id;
var reader = new FileReader();
reader.onload = function () {
base64String = reader.result;
imageBase64Stringsep = base64String;
imgToChange = getElement(`.change-this-image__${currentID}`);
imgToChange.src = base64String;
};
reader.readAsDataURL(file);
return base64String;
}
function log(msg) {
return console.log(msg);
}
function removeClass(el, _className = "active") {
if (el) {
return hasClass(el, _className) ? el.classList.remove(_className) : true;
}
return false;
}
function hasClass(el, _className = "active") {
if (el.classList.contains(_className)) {
return true;
} else {
return false;
}
return false;
}
function getElement(target, targetFrom = false) {
return targetFrom ?
targetFrom.querySelector(target) :
document.querySelector(target);
}
function getElements(target, targetFrom = false) {
return targetFrom ?
[...targetFrom.querySelectorAll(target)] :
[...document.querySelectorAll(target)];
}
function getElementById(target, targetFrom = false) {
return targetFrom ?
targetFrom.getElementById(target) :
document.getElementById(target);
}
function addClass(el, _className = "active") {
if (el) {
return !hasClass(el, _className) ? el.classList.add(_className) : true;
}
return false;
}
function getParent(el, idx) {
previouslyParent = el.parentElement;
for (let index = 0; index < idx - 1; index ) {
previouslyParent = previouslyParent.parentElement;
}
return previouslyParent;
}
function getOffset(el) {
const rect = el.getBoundingClientRect();
return {
top: rect.top window.scrollY,
left: rect.left window.scrollX
};
}
function objectToTagStyles(selector, styles) {
if (styles) {
var style = document.createElement("style");
resonanceCssString = `${selector} {`;
for (const [key, value] of Object.entries(styles)) {
resonanceCssString = `${key}:${value};`;
}
resonanceCssString = "}";
if (style.styleSheet) {
style.styleSheet.cssText = resonanceCssString;
} else {
style.appendChild(document.createTextNode(resonanceCssString));
}
document.getElementsByTagName("head")[0].appendChild(style);
return true;
}
return false;
}
function objectToCssTextStyles(styles) {
if (styles) {
resonanceCssString = "";
for (const [key, value] of Object.entries(styles)) {
resonanceCssString = `${key}:${value};`;
}
return resonanceCssString;
}
return false;
}
function getAttribute(element, attr, isReturnValue) {
return isReturnValue ?
element.attributes[attr].value :
element.attributes[attr];
}
function stringGen(yourNumber) {
var text = "";
var possible =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < yourNumber; i ) {
text = possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
let base64String = "";
function imageUploaded() {
var file = this["files"][0];
var currentID = this.id;
var reader = new FileReader();
reader.onload = function() {
base64String = reader.result;
imageBase64Stringsep = base64String;
imgToChange = getElement(`.change-this-image__${currentID}`);
imgToChange.src = base64String;
};
reader.readAsDataURL(file);
return base64String;
}
imgs = getElements("img");
svgs = getElements("svg");
getElement("body").style.position = "relative";
for (let imageElement of imgs) {
newChangeImageWrapper = document.createElement("label");
newChangeImageInput = document.createElement("input");
addClass(newChangeImageWrapper, "reverb-image-changer");
randomNewWapperId = stringGen(10);
randomNewInputId = stringGen(10);
currentImgOffset = getOffset(imageElement);
addClass(
newChangeImageWrapper,
`reverb-image-changer--id_${randomNewWapperId}`
);
newChangeImageWrapper.setAttribute("for", randomNewInputId);
newChangeImageInput.setAttribute("id", randomNewInputId);
newChangeImageInput.type = "file";
newChangeImageInput.onchange = imageUploaded;
newChangeImageWrapper.appendChild(newChangeImageInput);
addClass(imageElement, `change-this-image__${randomNewInputId}`);
currentImageBoundaries = imageElement.getBoundingClientRect();
currentWrapperStyles = {
width: `${currentImageBoundaries.width}px`,
height: `${currentImageBoundaries.height}px`,
position: "fixed",
top: `${currentImageBoundaries.y}px`,
left: `${currentImageBoundaries.x}px`
};
newChangeImageWrapper.style.cssText = objectToCssTextStyles(
currentWrapperStyles
);
getElement("body").appendChild(newChangeImageWrapper);
}
.reverb-image-changer {
display: block;
border: 1px solid transparent;
text-align: center;
color: white;
cursor: pointer;
margin-top: 0;
transition: .3s;
z-index: 999;
}
.reverb-image-changer:hover {
border-color: rgb(46, 204, 113);
cursor: pointer;
}
.reverb-image-changer input {
width: 0px;
height: 0px;
visibility: hidden;
position: absolute;
top: 0;
left: -100%;
}
<img src="https://picsum.photos/200/300" alt="" width="200" height="300">
<img src="https://picsum.photos/200/300" alt="" width="200" height="300">
<img src="https://picsum.photos/200/300" alt="" width="200" height="300">
<img src="https://picsum.photos/200/300" alt="" width="200" height="300">
CodePudding user response:
imgToChange.src = base64String;
needs to be inside the reader.onload
function. because the base64String
is empty where you are putting it right now.
hope it makes sense. it would make more sense if you check it in the debugger and press F8
to watch the flow of the code.
function log(msg){return console.log(msg); } function removeClass(el, _className="active"){if(el){return hasClass(el, _className) ? el.classList.remove(_className) : true; } return false; } function hasClass(el, _className="active"){if(el.classList.contains(_className)){return true; } else {return false; } return false; } function getElement(target, targetFrom=false){return targetFrom ? targetFrom.querySelector(target) : document.querySelector(target); } function getElements(target, targetFrom=false){return targetFrom ? [...targetFrom.querySelectorAll(target)] : [...document.querySelectorAll(target)]; } function getElementById(target, targetFrom=false){return targetFrom ? targetFrom.getElementById(target) : document.getElementById(target); } function addClass(el, _className="active"){if(el){return !hasClass(el, _className) ? el.classList.add(_className) : true; } return false; } function getParent(el, idx){previouslyParent = el.parentElement; for (let index = 0; index < idx - 1; index ) {previouslyParent = previouslyParent.parentElement; } return previouslyParent; } function getOffset(el) {const rect = el.getBoundingClientRect(); return {"top": rect.top window.scrollY, "left": rect.left window.scrollX }; } function objectToTagStyles(selector, styles){if(styles){var style = document.createElement('style'); resonanceCssString = `${selector} {`; for (const [key, value] of Object.entries(styles)) {resonanceCssString = `${key}:${value};`; } resonanceCssString = "}"; if (style.styleSheet) {style.styleSheet.cssText = resonanceCssString; } else {style.appendChild(document.createTextNode(resonanceCssString)); } document.getElementsByTagName('head')[0].appendChild(style); return true; } return false; } function objectToCssTextStyles(styles){if(styles){resonanceCssString = ''; for (const [key, value] of Object.entries(styles)) {resonanceCssString = `${key}:${value};`; } return resonanceCssString; } return false; } function getAttribute(element, attr, isReturnValue){return isReturnValue ? element.attributes[attr].value : element.attributes[attr]; } function stringGen(yourNumber){var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < yourNumber; i ){text = possible.charAt(Math.floor(Math.random() * possible.length)); } return text; }
let base64String = "";
function imageUploaded() {
var file = this['files'][0];
var reader = new FileReader();
reader.onload = function () {
base64String = reader.result;
imageBase64Stringsep = base64String;/*=====> 1.this executes after the imgTochange.src*/
imgToChange.src = base64String;
console.log(base64String);
}
imgToChange = getElement(`.change-this-image__${this.id}`);
/*imgToChange.src = base64String; =====> 1.this executes first,here base64String is empty*/
reader.readAsDataURL(file);
return base64String;
}
imgs = getElements('img');
svgs = getElements('svg');
getElement('body').style.position = 'relative';
for(let imageElement of imgs){
newChangeImageWrapper = document.createElement("label");
newChangeImageInput = document.createElement("input");
addClass(newChangeImageWrapper, 'reverb-image-changer');
randomNewWapperId = stringGen(10);
randomNewInputId = stringGen(10);
currentImgOffset = getOffset(imageElement);
addClass(newChangeImageWrapper, `reverb-image-changer--id_${randomNewWapperId}`);
newChangeImageWrapper.setAttribute("for", randomNewInputId);
newChangeImageInput.setAttribute("id", randomNewInputId);
newChangeImageInput.type = "file";
newChangeImageInput.onchange = imageUploaded;
newChangeImageWrapper.appendChild(newChangeImageInput)
addClass(imageElement, `change-this-image__${randomNewInputId}`);
currentImageBoundaries = imageElement.getBoundingClientRect();
currentWrapperStyles = {
"width": `${currentImageBoundaries.width}px`,
"height": `${currentImageBoundaries.height}px`,
"position": "fixed",
"top": `${currentImageBoundaries.y}px`,
"left": `${currentImageBoundaries.x}px`
}
newChangeImageWrapper.style.cssText = objectToCssTextStyles(currentWrapperStyles);
getElement('body').appendChild(newChangeImageWrapper);
}
.reverb-image-changer{
display: block;
border: 1px solid transparent;
text-align: center;
color: white;
cursor: pointer;
margin-top: 0;
transition: .3s;
z-index: 999;
}
.reverb-image-changer:hover{
border-color: rgb(46, 204, 113);
cursor: pointer;
}
.reverb-image-changer input{
width: 0px;
height: 0px;
visibility: hidden;
position: absolute;
top: 0;
left: -100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<img src="https://picsum.photos/200/300" alt="" width="200" height="300">
<img src="https://picsum.photos/200/300" alt="" width="200" height="300">
<img src="https://picsum.photos/200/300" alt="" width="200" height="300">
<img src="https://picsum.photos/200/300" alt="" width="200" height="300">
</body>
</html>