converting image and video data uri to base 64 - html

I was trying to encrypt image and video src by converting into base 64 encoded value. I had taken reference from https://www.iandevlin.com/blog/2012/09/html5/html5-media-and-data-uri
Following is my html code:
<!DOCTYPE html>
<html>
<body>
<video style="width: 640px; height: 360px;" onloadstart="" id="mediaplayer" oncontextmenu="return false;" controls preload src="" poster=""/>
</body>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script>
// To access player after its creation through jQuery use:
var videoSrc = 'http://clips.vorwaerts-gmbh.de/VfE_html5.mp4';
var imageSrc = 'http://www.w3schools.com/images/w3html5.gif';
var playerObj = $('#mediaplayer')[0];
var encodedSrc = btoa(playerObj.src);
var decodedSrc = atob(encodedSrc);
var playerObjPoster = playerObj.poster;
console.log(decodedSrc);
playerObj.src = "data:video/mp4;base64,"+btoa(videoSrc);
//playerObj.src = videoSrc;
playerObj.poster = 'data:image/gif;base64,'+btoa(imageSrc);
//playerObj.poster = imageSrc;
</script>
</html>
On runtime image and video src is showing as encoded value but neither image and neither video is displayed on the web page.
Any suggesstions ?

It does not work like this. You must base64 encode the actual contents of the file, not the path to the file. The link you used actually shows this in the example:
function getEncodedVideoString($type, $file) {
return 'data:video/' . $type . ';base64,' . base64_encode(file_get_contents($file));
}
Currently what is happening is that the browser is trying to use the decoded value (whis is a URI) as the actual image or video data and of course it fails.

Related

Wordpress json - How to use the content rendered from json

Using basic Wordpress basic Json in the format //domain.com/wp-json/wp/v2/pages/ I can access to a specific page content.
What I need to do is to use the rendered content as html of a blank page.
How to store this content into a variable so that I can use it? I suppose I shloud store into an array. Any sample?
Thank you.
How to store this content into a variable so that I can use it?
var x = data.content.rendered;
Where data is the JSON object you provided.
After this line is executed, x will contain HTML that you can use it in your project.
What I need to do is to use the rendered content as html of a blank page.
Any sample?
//change this values
var wpApiBaseURL = "http://localhost/wp-json/wp/v2/";
var pageId = 2; // id of the page to fetch
//
var container = document.getElementById("container");
// fetch specific page
fetch(wpApiBaseURL + "pages/" + pageId)
.then(function(rawResponse) {
return rawResponse.json();
})
.then(function(jsonResponse) {
// load successful and replaces html contents of the container div
container.innerHTML = jsonResponse.content.rendered;
})
.catch(function(error) {
container.innerText = "Error loading page";
});;
<!DOCTYPE html>
<body>
<div id="container">
Loading
</div>
</body>

How to Embed data (PDF Base 64) in angular 6 component

In my application in angular 6, I am showing Data(Report) in new window as follows.
*** result contains Base64 data***
if (result != null) {
const pdfWindow = window.open("");
pdfWindow.document.write("<html<head><title>Pathology Report</title><style>body{margin: 0px;}iframe{border-width: 0px;}</style></head>");
pdfWindow.document.write("<body><embed width='100%' height='100%' src='data:application/pdf;base64, " +
encodeURI(result) + "#toolbar=0&navpanes=0&scrollbar=0'></embed></body></html>")
Now what I want to do is like, I want to embed this data(result) in my angular component in tag.
My html code is as follows
<iframe [src]="PathReportString"></iframe>
and component.ts code is
this.PathReportString = (this.sanitizer.bypassSecurityTrustResourceUrl(result) as any).changingThisBreaksApplicationSecurity;
But it shows error "unsafe value used in a resource URL context".
The result get displayed properly in new window but when try to embed, it shows error.
How to embed data. Also my data is base64.
What is going wrong? Any help would be appreciated. Thank you.
It works. I wrote code in .html file as
<iframe id="ifrm" style="width: 100%; height: 100%;"></iframe>
and in component.ts file code is like,
this.PathReportString = 'data:application/pdf;base64,' + (this.sanitizer.bypassSecurityTrustResourceUrl(result) as any).changingThisBreaksApplicationSecurity;
top.document.getElementById('ifrm').setAttribute("src", this.PathReportString);
please add data:application/pdf;base64, before the base64 String
<iframe [src]="data:application/pdf;base64, PathReportString"></iframe>

One-click download button for a giphy gif

I want to create a one-click download link for images. I get inconsistent results with the html5 download attribute.
W3 schools has a working example triggering a download: https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_a_download
When I change the image urls to anything else it does not trigger a file download.
For example this code doesn't trigger a download:
<a href="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/687px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg" download>
Can anyone explain why?
I asked the same question, here is the code that worked for me:
(async () => {
//create new a element
let a = document.createElement('a');
// get image as blob
let response = await fetch('https://media2.giphy.com/media/DvyLQztQwmyAM/giphy.gif?cid=e9ff928175irq2ybzjyiuicjuxk21vv4jyyn0ut5o0d7co50&rid=giphy.gif');
let file = await response.blob();
// use download attribute https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Attributes
a.download = 'myGif';
a.href = window.URL.createObjectURL(file);
//store download url in javascript https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes#JavaScript_access
a.dataset.downloadurl = ['application/octet-stream', a.download, a.href].join(':');
//click on element to start download
a.click();
})();
In the w3schools example that you have attached, the link text which you should click on to start download is an image. They have put an image inside of an anchor tag (<a></a>) and then have given URL to the href attr of the anchor. Then if you change the href, the url will change without changing the image and you can start downloading by clicking on the image.
in the code that you have attached to your question (Which is working and download an image as a file if you add the </a> to the end of it.), you've given the URL of an image as href attr. So if you change the href, different file would be downloaded.
<a href="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/687px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg" download>click</a>
if you want to click on your image to start the download, you should put an image inside of the anchor and then gave the href attr, your file URL.
<a href="" download>
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/687px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg" alt="image" width="100" />
</a>
The problem of why it's not working is that the download attribute only works for same-origin URLs. You can find the details here MDN Docs
As for an alternative, you can use some javascript like this to achieve the same.
function download_img(e,link){
var image = new Image();
image.crossOrigin = "anonymous";
image.src = link;
image.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size
canvas.getContext('2d').drawImage(this, 0, 0);
var blob;
// ... get as Data URI
if (image.src.indexOf(".jpg") > -1) {
blob = canvas.toDataURL("image/jpeg");
} else if (image.src.indexOf(".png") > -1) {
blob = canvas.toDataURL("image/png");
} else if (image.src.indexOf(".gif") > -1) {
blob = canvas.toDataURL("image/gif");
} else {
blob = canvas.toDataURL("image/png");
}
tempbtn = document.createElement('a');
tempbtn.href = blob;
tempbtn.download = 'image.jpg'; // or define your own name.
tempbtn.click();
tempbtn.remove();
};
}
<!DOCTYPE html>
<html>
<body>
<a href="#" onclick="download_img(this,'https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/687px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg')" >Download image
</a>
<p><b>Note:</b> The download attribute is not supported in Edge version 12, IE, Safari 10 (and earlier), or Opera version 12 (and earlier).</p>
</body>
</html>

JavaScript: Load an image from javascript then wait for the "load" event of that image

I have a page that displays a picture in high quality. The pictures typically take a while to load. I have a jQuery function that runs on load of the picture #image I want this function to pre-load other images 1 at a time in the order they will appear.
So: on if I am on the 1st picture, it should load picture 1 and display it, then pre-load/cache the second picture when pic1 is done. The pictures being loaded all have a caching header attached already. When pic2 is done loading, pic3 should begin loading. In case you are wondering, I have a cgi backend that is able to print things in loops and such.
So far I have the following working:
$('#image').load(function() {
preLoad2 = new Image()
preLoad2.src = "pic2"
})
I can then continue this with another function with the same $('#image').load(function() { } line, but how do I make it so the next picture doesn't begin loading until this one is completely loaded. I would prefer not to use a timed delay as that is not very accurate.
Here is what I have currently. I am using a bash cgi script in this example.
#set a loop counter
# variables will be refered to as $[var-name]
count=1
first=true
#loop through all images that need pre-loading
for file in *
do
#check if the picture matches the search criteria
if [[ "$file" = *$lowerSearch* ]]
then
#create a js script
echo "<script language=\"javascript\" type=\"text/javascript\">"
echo "function load$count() {"
echo " preLoad$count = new Image()"
echo " preLoad$count.src = \"?loadFile=$file\""
echo "}"
#the first one of these functions should be bound to the main image load event
if [ "$first" = 'true' ]
then
echo "document.getElementById('image').onload = load$count()"
#the 2nd and on should be bound to the pre-load of the previous picture
else
echo " preLoad$last.onload = load$count()"
#end if
fi
echo "</script>"
#store the current count so that the next time through it can be used to call the last loaded picture
last=$count
first=false
#add 1 to count
count=$((count+1))
#end if
fi
#end loop
done
How this works: Loops through pictures. If the picture matches the search criteria then run the main code...otherwise skip loop. In the search criteria, it creates a js script that includes a function. the function loads the picture that the loop is currently referring to. It then creates an onLoad function that refers to the last picture pre-loaded and sets an onLoad event to it that runs the function just created.
I believe this question's answer is somewhat related to this question
First create JSON record of images like this
var imageRecord = ['image1.jpg',
'image2.jpg',
'image3.jpg',
'image4.jpg',
'image5.jpg'];
then create function to load image one after another
function loadAllImages(index){
if( index >= imageRecord.length ){
return;
}
//create image object
var image = new Image();
//add image path
image.src = imageRecord[index];
//bind load event
image.onload = function(){
//now load next image
loadAllImages(index + 1);
}
}
hope this small snippet will help you.
to understand whole concept of preload images using javascript, please visit http://zainultutorials.blogspot.in/2013/11/preload-images-using-javascript.html
In the past I've used something similar to this image preloader:
http://www.webreference.com/programming/javascript/gr/column3/index.html
The formatting on the code is weird but the code itself is good. After setting up that ImagePreloader "class" I used a method like this:
function preloadImages(imageSRCs){
var loadingMessage = $('<div/>').addClass('loading').html('<h1>LOADING</h1>');
// stay classy: tell the user you're loading images
$('#content').append(loadingMessage);
// this imgPreloader takes care of loading the images
imgPreloader = new ImagePreloader(imageSRCs, function(imgArr, numLoaded){
if(this.nImages == numLoaded){
loadingMessage.remove();
//do whatever you want with the images here
for(var i = 0; i < imgArr.length; i++){
var pathIdPattern = new RegExp("[^/]+\\.");
var imgName = pathIdPattern.exec(imgArr[i].src)[0];
var imgId = imgName.substring(0, imgName.length-1);
$('div#images').append($(imgArr[i]).hide().attr("id", imgId));
}
}else{
loadingMessage.text('Sorry, there was a problem loading the site : / ');
console.error("Only " + numLoaded + " of " + this.nImages + " images loaded successfully.");
}
});}
Where the imageSRCs parameter was just a string array of the image paths. Maybe it's a more involved solution to what you're looking for but I hope it helps!
if you have the images an array of urls you can do something like this: demo
<div id="cont"></div>
<script type="text/javascript">
function loadImagesInSequence(images) {
if (!images.length) {
return;
}
var img = new Image();
//Remove if from the array list and return it to the variable
var url = images.shift();
img.onload = function(){ loadImagesInSequence(images) };
img.src = url;
$("#cont").append(img);
}
loadImagesInSequence(['http://www.nasa.gov/centers/goddard/images/content/433226main_Misti_ComaCluster.jpg',
'http://www.hdwallpapers.in/walls/cold_universe-wide.jpg', 'http://scienceblogs.com/startswithabang/files/2013/05/chemical_composition_universe.jpeg']);
</script>
or if you have the image tags in your page you can go with something like this: demo
<img id="img1" src="http://miniontours.yzi.me/loading.gif" data-image="http://www.nasa.gov/centers/goddard/images/content/433226main_Misti_ComaCluster.jpg" />
<img id="img2" src="http://miniontours.yzi.me/loading.gif" data-image="http://www.hdwallpapers.in/walls/cold_universe-wide.jpg" />
<img id="img3" src="http://miniontours.yzi.me/loading.gif" data-image="http://scienceblogs.com/startswithabang/files/2013/05/chemical_composition_universe.jpeg" />
<script type="text/javascript">
var imgs = [];
$("img").each(function(){
imgs.push({
"ID": this.id,
"src" : $(this).data("image")
});
});
loadImagesInSequence(imgs);
function loadImagesInSequence(images) {
if (!images.length) {
return;
}
var img = images.shift();
var url = img.src;
img = $("#"+img.ID);
img.load(function(){ loadImagesInSequence(images); });
img.attr("src",url);
}
</script>

Storing HTML5 canvas containing images

How do you store a canvas that contains images using the toDataURL method? Everything works fine for text and drawing, but I don't know how to handle images. Any help would be appreciated. Thanks
I have modified my question as follows:
This works when the image is pulled directly from a .png. However, when I call the Google Charts API, toDataURL doesn't work even though the image renders correctly on the canvas. Google Charts is returning a .png. Anyone have any ideas? Thanks.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" charset="utf-8">
function test() {
var c = document.getElementById("drawing-canvas");
var cxt = c.getContext("2d");
// This doesn't work.
//var imgsrc = 'http://chart.apis.google.com/chart?cht=tx&chf=bg,s,ffffff&chco=000000&
chl=a';
// This works
var imgsrc = 'chart.png';
var img = new Image();
img.src = imgsrc;
cxt.drawImage(img,0,0);
}
function wr() {
var cc = document.getElementById("drawing-canvas");
var url = cc.toDataURL();
var newImg = document.createElement("img");
newImg.src = url;
document.body.appendChild(newImg);
}
</script>
</head>
<body onload = "test();">
<canvas id="drawing-canvas" width = "500px" height = "500px" style="background-color:
#ffffff; border: 2px solid #000000;">
Your browser does not support the canvas element.
</canvas>
<input type = "button" value = "go" onclick = "wr();">
</body>
</html>
First of all, your chart didn't even render on the canvas when I tested it. You need to wait for the image to load. Your chart.png image probably loads instantaneously since it's cached, but the one generated by Google Charts API isn't. This is what you should do:
var img = new Image();
img.onload = function()
{
cxt.drawImage(img,0,0);
}
img.src = imgsrc;
Aside from that, you must be getting a SECURITY_ERR in your browser's console. This is because the Canvas security model doesn't allow you to export images coming from an external URL. You should use a server-side language to save the Google Charts image to your server, then load it from there.
The HTML canvas element has a method called toDataURL, that will return a data URL image representing the canvas. You can check the documentation API on the MDN.
Specifically, it says about toDataURL:
toDataURL(in optional DOMString type, in any ...args)
returns DOMString
Returns a data: URL containing a representation of the image in the format specified by type (defaults to PNG).
If the height or width of the canvas is 0, "data:," representing the empty string, is returned.
If the type requested is not image/png, and the returned value starts with data:image/png, then the requested type is not supported.
Chrome supports the image/webp type.
If the requested type is image/jpeg or image/webp, then the second argument, if it is between 0.0 and 1.0, is treated as indicating image quality; if the second argument is anything else, the default value for image quality is used. Other arguments are ignored.
And provides and example on how to use it:
function test() {
var canvas = document.getElementById("canvas");
var url = canvas.toDataURL();
var newImg = document.createElement("img");
newImg.src = url;
document.body.appendChild(newImg);
}
In this example, we use the dataURL as the source attribute of an img element, but you can do whatever you want you it (like storing it somewhere, or sending it to the server with an ajax call).
Note that most of the methods involved in drawing on canvas are methods of drawing context (obtained by a call to getContext), while this method is one of the canvas element.