Base64 image not opening up when converted from Image URL - javascript

I am converting an image to Base64 from Image URL using canvas. The approach I am taking is similar to below 2 links but the converted Base64 string is not opening up the image when viewed in Chrome Tab.
Links
CONVERT Image url to Base64
(1st answer with 81 thumbs up).
https://jsfiddle.net/3qshvc54/
I tried consoling the img, canvas, ctx in fiddle and my code. The console output is the same. Please see below screenshots.
If I do it by fiddle the converted Base64 URL opens up fine in a new tab, but the one generated from my code does not display an image when opened up in a new tab.
I am using same Image URL in my code and Fiddle
Console screenshot when running from my code
Console screenshot when running from Fiddle
The Base64 generated from my code:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEQAAABDCAYAAAAlFqMKAAAApklEQVR4Xu3VsQ0AIAwEMbL/0tShQLrejHB6kzneKjB67AKCPIsQRJD/J2EhFmIh6ZAigwwyyKQCyCCTBuPKIIMMMqkAMsikwbgyyCCDTCqADDJpMK4MMsggkwogg0wajCuDDDLIpALIIJMG48oggwwyqQAyyKTBuDLIIINMKoAMMmkwrgwyyCCTCiCDTBqMK4MMMsikAsggkwbjyiCDDDKpADL/XBfFQABED54eAwAAAABJRU5ErkJggg==
I tried validating the same online it shows that the Base64 string is valid:
When I try to decode the same:
It seems that the result of decoding is a binary data (MIME type detected as “image/png”) and because of this the data from “Text” may be damaged during the output.
My code:
<div className='image-root'>
<img id={`imageBlock-${props.photoBoxID}`} className="multi-image-photo" src={props.imgUrl} alt="photo"></img>
</div>
getBase64Image = (img) => {
img.crossOrigin = 'Anonymous';
var canvas = document.createElement("CANVAS");
canvas.width = img.width;
canvas.height = img.height;
console.log('img', img);
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
console.log('canvas', canvas);
console.log('ctx', ctx);
var dataURL = canvas.toDataURL();
console.log('dataURL', dataURL);
}
componentDidUpdate(prevProps, prevState){
if(this.props.isUploaded && (prevProps.isUploaded !== this.props.isUploaded)){
let imageRef = document.getElementById(`imageBlock-${this.props.photoBoxID}`);
imageRef.onload = this.getBase64Image(imageRef);
}
}
Can you suggest why the Base64 string generated is not opening up fine if converted from my code, though it opens up from Fiddle? Is it corrupted?

onload is an event you need function there and in that function you need to update src.
componentDidUpdate(prevProps, prevState){
if(this.props.isUploaded && (prevProps.isUploaded !== this.props.isUploaded)){
let imageRef = document.getElementById(`imageBlock-${this.props.photoBoxID}`);
imageRef.onload = () => {
delete imageRef.onload;
imageRef.src = this.getBase64Image(imageRef);
};
}
}
but better is to add base64 image to state and don't use getElementById directly in React applications.
EDIT:
for infinite loop I would create 2 images, if you need to render image on canvas you usually render outside of DOM:
componentDidUpdate(prevProps, prevState){
if(this.props.isUploaded && (prevProps.isUploaded !== this.props.isUploaded)){
let imageRef = document.getElementById(`imageBlock-${this.props.photoBoxID}`);
var srcImg = new Image();
srcImg.onload = () => {
imageRef.src = this.getBase64Image(srcImg);
};
srcImg.src = prevProps.imgUrl;
}
}
and remove the props from JSX template you will not need it.
And side note: if you have big image it's better to create object URL from blob, because there is limit of data that can be put into URL (for smaller images it should not matter):
function asObjectUrl(canvas) {
return new Promise(function(resolve) {
canvas.toBlob(function(blob) {
resolve(URL.createObjectURL(blob));
});
});
}
The object url need to be removed when not needed to not create memory leaks (use URL.revokeObjectURL)

change your img's src attribute adding src="data:image/jpeg;base64 tag with the encoded string like below:
<img id={`imageBlock-${props.photoBoxID}`} className="multi-image-photo" src="data:image/jpeg;base64, ${props.imgUrl}" alt="photo"></img>
This should work.
N.B.: Please check your imageString variable carefully, I might have used the wrong one, not sure.

Related

Copy QR CODE image to clipboard and paste to share. I use Vuejs? [duplicate]

Seemingly, you can't (yet) programmatically copy an image to the clipboard from a JavaScript web app?
I have tried to copy a text in clipboard , and it's worked.
Now I would like to copy an image and after I press ctrl+v to paste into Word or Excel or Paint.
$(function() {
$("#btnSave").click(function() {
html2canvas($("#container1"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
Canvas2Image.saveAsPNG(canvas);
$("#img-out").append(canvas);
}
});
});
});
For those still looking, the ClipboardAPI now works with png images.
try {
navigator.clipboard.write([
new ClipboardItem({
'image/png': pngImageBlob
})
]);
} catch (error) {
console.error(error);
}
This worked across all browsers (as of 2016). I have uploaded on GitHub as well: https://github.com/owaisafaq/copier-js
//Cross-browser function to select content
function SelectText(element) {
var doc = document;
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
}
$(".copyable").click(function(e) {
//Make the container Div contenteditable
$(this).attr("contenteditable", true);
//Select the image
SelectText($(this).get(0));
//Execute copy Command
//Note: This will ONLY work directly inside a click listenner
document.execCommand('copy');
//Unselect the content
window.getSelection().removeAllRanges();
//Make the container Div uneditable again
$(this).removeAttr("contenteditable");
//Success!!
alert("image copied!");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="copyable">
<img src="https://via.placeholder.com/80" alt="Copy Image to Clipboard via Javascript." />
</div>
<div class="copyable">
<img src="https://via.placeholder.com/80" alt="Copy Image to Clipboard via Javascript." />
</div>
So, i created the perfect solution with 1 liner-kinda solution to convert something with html2canvas to a canvas and then produce the image of it and then save it to clipboard as png. For example,
HTML:
<div id="copyToImage">Hello World!</div>
JavaScript:
$("#copyToImage").click(function() {
html2canvas(document.querySelector("#copyToImage")).then(canvas => canvas.toBlob(blob => navigator.clipboard.write([new ClipboardItem({'image/png': blob})])));
});
You are right. There is no support to copy image data into clipboard in chrome yet. https://bugs.chromium.org/p/chromium/issues/detail?id=150835.
Looks like it has been open for about 4 years now.
There is a clipboard API spec that is coming up though
https://w3c.github.io/clipboard-apis/
Well, this is my first post in here with an answer i guess :)
Actually i'm currently using cefsharp web browser component one of my project, cefsharp run on chrome based browser and i want to copy img element one of webpage
With cefsharp you can manipulate browser only javascript, so i think we can handle it with using canvas element.
/*
'cause of lorempixel timeout, i used img onload function.
*/
function copyImage() {
var imgCap = document.getElementById('imgCap');
var imgCanvas = document.createElement('canvas');
imgCanvas.id = 'imgCanvas';
imgCanvas.height = 40;
imgCanvas.width = 120;
document.body.appendChild(imgCanvas);
var originalContext = imgCanvas.getContext('2d');
originalContext.drawImage(imgCap, 0, 0);
//return imgCanvas.toDataURL();
}
//document.onload = copyImage();
<img id="imgCap" src="http://lorempixel.com/120/40" onload="copyImage();"/>
with return imgCanvas.toDataURL(); you can get base64 encoded value and use wherever you want.
this is my cefsharp code, it's working.
string copyImageOtClipboardScript = "(function(){ try{var imgCap = document.getElementById('imgCap'); var imgCanvas = document.createElement('canvas'); imgCanvas.id = 'imgCanvas'; imgCanvas.height = 40; imgCanvas.width = 120; document.body.appendChild(imgCanvas); var originalContext = imgCanvas.getContext('2d'); originalContext.drawImage(imgCap, 0, 0); return imgCanvas.toDataURL(); }catch(e){ alert(e); } })();";
var task = chromeBrowser.EvaluateScriptAsync(copyImageOtClipboardScript).ContinueWith(x =>
{
var resp = x.Result;
if (resp.Success)
{
this.Invoke((MethodInvoker)delegate
{
Bitmap bmp = null;
string captchaResult = "", captchaBase64;
var bytes = Convert.FromBase64String(resp.Result.ToString().Replace("data:image/png;base64,", ""));
using (var imageFile = new FileStream("temp_captcha.png", FileMode.Create))
{
imageFile.Write(bytes, 0, bytes.Length);
imageFile.Flush();
}
});
}
});
This can be achieved by using the Clipboard API, which does require that your server is secured. The basic idea is to convert your image to a blob before writing it to the clipboard as an image.
const img = document.querySelector("#b64-img");
const copyBtn = document.querySelector("#copy");
copyBtn.onclick = e => {
const canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext("2d").drawImage(img, 0, 0, img.width, img.height);
canvas.toBlob((blob) => {
navigator.clipboard.write([
new ClipboardItem({ "image/png": blob })
]);
}, "image/png");
};
<img id="b64-img" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQoAAAFmCAMAAACiIyTaAAABv1BMVEUAAAB5S0dJSkpISkpLTU3pSzzoTD3oSzzoTD3kSj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GyBimOJZYYA1TR/alCbpakMJ4EyHEs7liSfiFF8aw4xlcAVURHU44fikjGw/xlGypJcRPel//xvom5fCR/wNfoyq4rzpRQmGJcAqnC3au4bAj5sr+u6fZ7qB0oIYT6dT3HZgXeCUjRA0zdPCMI2sCGYi73Dpjk2NC8QgioCuRoFWxtH4Rwg5k2oFj0L2UDb96VHRchuCqQyylnM5LD4jEOAnsbhKMT7R0vjgVoFaiGqQgzoxDoKKQEQcNv767LV+6xA9gqvPhc/+Qx4RAFjBNR8D6lHihgq0B3mEr19DpbzF5fnnUUGhlRaN7VrstO/jIArgJhTLlgnO6bgYnCRUGAriK6uh8vIgjQVaBSDb/lNjomlNA/p1AVlri1/cr4FYV3Q6Eq7KlU3pGDv6ECNh8qPlQkKeHLVdBjEHT4xf9W9PgxZRdBxmn5x3Ssl3mpxU7wWw4Cilvu+D47vXnIjpafQqcPccf41PXTKdnFw8+gjKBR9rOwW+V9P4uOhyBR6fqZdK3z8T8sDJf52bSQDdplnk0oeH4efWSD85vngEG+CWE5KAk/DyD7Rb6JPqrXB4OeZjQaDYfDe8NQMxr1NINB/Xri59BBEPByTcjqbmrDbodzXby/IfzMlAs11SasXTDgKrwcEyLQJqxdbCYCdkBQJ1MEN+mwchHKdBlMANk2K+nvXtBgZ0zYyZiGXCRtCAWmZFVOq6LSnwcbEecsjF2wkUIIxQ5KJ4KPERyclrGg8XHDiDjbxjTYYKlEBOPNzwMECtfptjo+8yVdNYLqzoi4zMY0CMJ1ozH+3KsjqJTqg95w3G5Xq5erqLbb4/tRb3CD/g9u9h1zNLq/115iqqm0Y8a6fo508azf/FMFPwB+4ZiyTYnf/gAAAABJRU5ErkJggg==">
<br>
<button id="copy">Copy Above Image</button>
This will allow you to paste your image to Photoshop and other image-applications.
Check out this guide to copying and pasting with JavaScript: https://www.lucidchart.com/techblog/2014/12/02/definitive-guide-copying-pasting-javascript/
According to this, Chrome, Safari, and Firefox all support copying images along with plain text, while IE only allows copying text. The page linked above describes how this service uses an extension to add this functionality to a context menu, but it appears that several browsers support programmatic copying of images.
const copyImageToClipboard = async () => {
try {
await navigator.clipboard.write([
new ClipboardItem({
'image/png': await fetch(img).then((r) => r.blob()),
}),
]);
} catch (error) {
console.error(error);
}
};
You might run into CORS errors testing on localhost. But you can install a CORS extension to get rid of that issue :)
var image = new Image();
image.src = url;
copyImageToClipboard(image.src);
install it from https://www.npmjs.com/package/copy-image-clipboard
Here is the best answer i found for you, very simple and its working 100% exactly what you need.
await navigator.clipboard.writeText(code);
Check out this link: enter link description here
You cannot copy to clip board with Javascript for security reasons, a work around can be found in a discussion here. Involves flash.Click button copy to clipboard using jQuery

Specifying the name of a video when src is dataURL

Using JS I creating a video from a series of screen grabs from a canvas element. E.g.
let encoder = new Whammy.Video(25); //25 is fps
for(...) {
//do stuff on canvas every x ms
....
//get a dataURL from the canvas
let dataURL = canvas.toDataURL('image/webp');
//add the dataURL to the encoder
encoder.add(dataURL);
}
// Now we want to create a video from the array of data urls
encoder.compile(false, (webm_output) => {
//webm_output is a blob
//create dataURL from blob
let url = URL.createObjectURL(webm_output);
let vid = documentGetElementById('myVid');
vid.src = url;
})
This all works, however, if the user would like to download the video (using in built controls), the name of the video is a random string.
Is it possible to manually specify the name?
On this demo:
<a style="" id="download" download="clock.webm" href="blob:[blob-url]">Download WebM</a>
The video name and extension is provided using the download= attribute.

Refresh image element after altering src with base64

I'm using jquery cropbox for a little project.
First the <img> is a default image, then i do a upload and FileReader for changing the image to a locally stored image.
like this
$('#selectfiledialog').change(function(evt){
var tgt = evt.target || window.event.srcElement,
files = tgt.files;
if (FileReader && files && files.length) {
var fr = new FileReader();
fr.onload = function () {
$('#the_image').attr('src', fr.result);
}
fr.readAsDataURL(files[0]);
}
});
However, when i will start the croping function on this image, it has the old values of the default image here, a 500x500 image.
So, when I will do the croping it has not got the new specs.
How can i now refresh that img element based on the new src? "add '?' + Math.random();" or date string is the only thing I've found but the new url is base64 encoded so that will not work.
Any ideas?
1 . Create a container for the image before all;
2 . Delete the image and add another image in the container you created.
Note: If you do this you will lost references to the element of the image because it'll be removed. Avoid making continued references to the image, var img = $('#the_image'), i.e.
Your HTML should be similiar to:
<div id="img_container">
<img id="the_image" src=""/>
</div>
Change the script line:
$('#the_image').attr('src', fr.result);
to:
$('#the_image').remove();
$('img_container')append('<img id="the_image" src="' + fr.result + '"/>');

converting a DIV to base64

How do I convert items inside a DIV to base64? See examle FIddle
html:
<div id="img2b64"> <img src="http://indianapublicmedia.org/stateimpact/files/2013/01/apple-image-300x300.jpg"> <div><br />
jQuery:
$('#ss').click(function(event){
var imageUrl = $('#img2b64').find('input[name=url]').val();
console.log('imageUrl', imageUrl);
convertImgToBase64(imageUrl, function(base64Img){
$('.output')
.find('textarea')
.val(base64Img)
.end()
.find('a')
.attr('href', base64Img)
.text(base64Img)
.end()
.find('img')
.attr('src', base64Img);
});
event.preventDefault();
});
function convertImgToBase64(url, callback, outputFormat){
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var img = new Image;
img.crossOrigin = 'Anonymous';
img.onload = function(){
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img,0,0);
var dataURL = canvas.toDataURL(outputFormat || 'image/png');
callback.call(this, dataURL);
// Clean up
canvas = null;
};
img.src = url;
}
var imageUrl = $('#img2b64').find('input[name=url]').val();
There is no <input name="url"> in your code so this is returning undefined. Perhaps you meant:
var imageUrl = $('#img2b64').find('img').prop("src");
However you'll find that this introduces its own error:
Image from origin 'http://indianapublicmedia.org' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
Meaning that you can't load that image into a Canvas because the target server does not support CORS. You'll either have to download that image to your own server first & load it into your canvas from there. Either that or enable CORS on indianapublicmedia.org
To problem that I see directly is in your jQuery where you do:
var imageUrl = $('#img2b64').find('input[name=url]').val();
Probably the console.log() below that line doesn't give you any valid URL, that should ring a bell. So the line above the console.log() doesn't do it's job.
That's because you are looking for any <input /> element (with name attribute = "url") inside the DIV with ID "img2b64". Also you are getting the value of the element with val(). You probably wanted to do something differently there.
If you want to get all images inside the DIV, then you need to simply look for img. To get the src attribute, do attr('src'):
var imageUrl = $('#img2b64').find('img').attr('src');
If you want to add an additional check for images with non-data src, do:
var imageUrl = $('#img2b64').find('img:not([src^="data"])').attr('src');
I did not check if the rest of the code (e.g. convertImgToBase64() function) is correctly working. You should always specify in your question what does work and what doesn't to get the best answers on SE.

How to get Base64 string out of HTML

I have a div containing an image and some text. The user is able to customize it. Once his modifications are done, I would like to save the div as an image with the text on it.
Just like if he took a screenshot.
I am able to save images from Base64 strings in my PHP side but I can't get the correct Base64 from the HTML.
So, I would like to know how to get the base64 from the HTML inside my div, using JavaScript or jQuery. I could also add plugins.
Try
var elem = $("div")[0].outerHTML;
var blob = new Blob([elem], {
"type": "text/html"
});
var reader = new FileReader();
reader.onload = function (evt) {
if (evt.target.readyState === 2) {
console.log(
// full data-uri
evt.target.result
// base64 portion of data-uri
, evt.target.result.slice(22, evt.target.result.length));
// window.open(evt.target.result)
};
};
reader.readAsDataURL(blob);
jsfiddle http://jsfiddle.net/guest271314/9mg5sf7o/
Try html2canvas
http://html2canvas.hertzen.com/examples.html
html2canvas($("#div"), {
onrendered: function(canvas) {
var myImage = canvas.toDataURL("img/png");
window.open(myImage);
}
});

Categories