ID3 - base64 cannot set as src for img - javascript

I just came the ID3 API across to get the cover of an audio file.
The base64 which is created by the API really good cannot be declarated in a img tag's src. The script don't even try to set a new src for the img tag.
https://github.com/aadsm/JavaScript-ID3-Reader
Here is my try:
<a class="uploaded_file"><img src="/symbol/audio.png"></a>
function getAudioCover(url) {
var tags = ID3.getAllTags(url);
var image = tags.picture;
if (image) {
var base64String = "";
for (var i = 0; i < image.data.length; i++) {
base64String += String.fromCharCode(image.data[i]);
}
var base64 = "data:" + image.format + ";base64," +
window.btoa(base64String);
return base64;
}
else {
return "/symbol/audio.png";
}
}
var uploadedFiles = 0;
var file_cover;
ID3.loadTags("audio.mp3", function() {
file_cover = getAudioCover("audio.mp3");
console.log(file_cover);
}, {
tags: ["picture"]
});
$('.uploaded_file:eq(' + uploadedFiles + ')').find('img').attr("src", file_cover);
The console gives me this out: https://jsfiddle.net/f1wzbtyh/
How do I get this working?
Is there a overflow of string length for jquery or for src attribute?

Place call to .attr() within callback function. file_cover may not be defined when referenced outside of .loadTags call.
ID3.loadTags("audio.mp3", function() {
file_cover = getAudioCover("audio.mp3");
console.log(file_cover);
$('.uploaded_file:eq(' + uploadedFiles + ')')
.find('img').attr("src", file_cover);
}, {
tags: ["picture"]
});

Related

how i can insert image in header of word document by JavaScript and jQuery

By Using jquery.wordexport.js and FileSaver.js I am getting a word document created with given data , what i have to change in jquery.wordexport.js to get image in header of the word document.
Please suggest with code or links will be appreciated a lot.
Thanks in advance.
My jquery.wordexport.js looks as below
if (typeof jQuery !== "undefined" && typeof saveAs !== "undefined") {
(function($) {
$.fn.wordExport = function(fileName) {
fileName = typeof fileName !== 'undefined' ? fileName : "jQuery-Word-Export";
var static = {
mhtml: {
top: "Mime-Version: 1.0\nContent-Base: " + location.href + "\nContent-Type: Multipart/related; boundary=\"NEXT.ITEM-BOUNDARY\";type=\"text/html\"\n\n--NEXT.ITEM-BOUNDARY\nContent-Type: text/html; charset=\"utf-8\"\nContent-Location: " + location.href + "\n\n<!DOCTYPE html>\n<html>\n_html_</html>",
head: "<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n<style>\n_styles_\n</style>\n</head>\n",
body: "<body>_body_</body>"
}
};
var options = {
maxWidth: 624
};
// Clone selected element before manipulating it
var markup = $(this).clone();
// Remove hidden elements from the output
markup.each(function() {
var self = $(this);
if (self.is(':hidden'))
self.remove();
});
// Embed all images using Data URLs
var images = Array();
var img = markup.find('img');
for (var i = 0; i < img.length; i++) {
// Calculate dimensions of output image
var w = Math.min(img[i].width, options.maxWidth);
var h = img[i].height * (w / img[i].width);
// Create canvas for converting image to data URL
var canvas = document.createElement("CANVAS");
canvas.width = w;
canvas.height = h;
// Draw image to canvas
var context = canvas.getContext('2d');
context.drawImage(img[i], 0, 0, w, h);
// Get data URL encoding of image
var uri = canvas.toDataURL("image/png");
$(img[i]).attr("src", img[i].src);
img[i].width = w;
img[i].height = h;
// Save encoded image to array
images[i] = {
type: uri.substring(uri.indexOf(":") + 1, uri.indexOf(";")),
encoding: uri.substring(uri.indexOf(";") + 1, uri.indexOf(",")),
location: $(img[i]).attr("src"),
data: uri.substring(uri.indexOf(",") + 1)
};
}
// Prepare bottom of mhtml file with image data
var mhtmlBottom = "\n";
for (var i = 0; i < images.length; i++) {
mhtmlBottom += "--NEXT.ITEM-BOUNDARY\n";
mhtmlBottom += "Content-Location: " + images[i].location + "\n";
mhtmlBottom += "Content-Type: " + images[i].type + "\n";
mhtmlBottom += "Content-Transfer-Encoding: " + images[i].encoding + "\n\n";
mhtmlBottom += images[i].data + "\n\n";
}
mhtmlBottom += "--NEXT.ITEM-BOUNDARY--";
//TODO: load css from included stylesheet
var styles = "";
// Aggregate parts of the file together
var fileContent = static.mhtml.top.replace("_html_", static.mhtml.head.replace("_styles_", styles) + static.mhtml.body.replace("_body_", markup.html())) + mhtmlBottom;
// Create a Blob with the file contents
var blob = new Blob([fileContent], {
type: "application/msword;charset=utf-8"
});
saveAs(blob, fileName + ".doc");
};
})(jQuery);
} else {
if (typeof jQuery === "undefined") {
console.error("jQuery Word Export: missing dependency (jQuery)");
}
if (typeof saveAs === "undefined") {
console.error("jQuery Word Export: missing dependency (FileSaver.js)");
}
}
My FileSaver.js is as below
/*! #source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
var saveAs=saveAs||function(e){"use strict";if("undefined"==typeof navigator||!/MSIE [1-9]\./.test(navigator.userAgent)){var t=e.document,n=function(){return e.URL||e.webkitURL||e},o=t.createElementNS("http://www.w3.org/1999/xhtml","a"),r="download"in o,i=function(e){var t=new MouseEvent("click");e.dispatchEvent(t)},a=/Version\/[\d\.]+.*Safari/.test(navigator.userAgent),c=e.webkitRequestFileSystem,d=e.requestFileSystem||c||e.mozRequestFileSystem,u=function(t){(e.setImmediate||e.setTimeout)(function(){throw t},0)},s="application/octet-stream",f=0,l=4e4,v=function(e){var t=function(){"string"==typeof e?n().revokeObjectURL(e):e.remove()};setTimeout(t,l)},p=function(e,t,n){t=[].concat(t);for(var o=t.length;o--;){var r=e["on"+t[o]];if("function"==typeof r)try{r.call(e,n||e)}catch(i){u(i)}}},w=function(e){return/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)?new Blob(["\uFEFF",e],{type:e.type}):e},y=function(t,u,l){l||(t=w(t));var y,m,S,h=this,R=t.type,O=!1,g=function(){p(h,"writestart progress write writeend".split(" "))},b=function(){if(m&&a&&"undefined"!=typeof FileReader){var o=new FileReader;return o.onloadend=function(){var e=o.result;m.location.href="data:attachment/file"+e.slice(e.search(/[,;]/)),h.readyState=h.DONE,g()},o.readAsDataURL(t),void(h.readyState=h.INIT)}if((O||!y)&&(y=n().createObjectURL(t)),m)m.location.href=y;else{var r=e.open(y,"_blank");void 0===r&&a&&(e.location.href=y)}h.readyState=h.DONE,g(),v(y)},E=function(e){return function(){return h.readyState!==h.DONE?e.apply(this,arguments):void 0}},N={create:!0,exclusive:!1};return h.readyState=h.INIT,u||(u="download"),r?(y=n().createObjectURL(t),void setTimeout(function(){o.href=y,o.download=u,i(o),g(),v(y),h.readyState=h.DONE})):(e.chrome&&R&&R!==s&&(S=t.slice||t.webkitSlice,t=S.call(t,0,t.size,s),O=!0),c&&"download"!==u&&(u+=".download"),(R===s||c)&&(m=e),d?(f+=t.size,void d(e.TEMPORARY,f,E(function(e){e.root.getDirectory("saved",N,E(function(e){var n=function(){e.getFile(u,N,E(function(e){e.createWriter(E(function(n){n.onwriteend=function(t){m.location.href=e.toURL(),h.readyState=h.DONE,p(h,"writeend",t),v(e)},n.onerror=function(){var e=n.error;e.code!==e.ABORT_ERR&&b()},"writestart progress write abort".split(" ").forEach(function(e){n["on"+e]=h["on"+e]}),n.write(t),h.abort=function(){n.abort(),h.readyState=h.DONE},h.readyState=h.WRITING}),b)}),b)};e.getFile(u,{create:!1},E(function(e){e.remove(),n()}),E(function(e){e.code===e.NOT_FOUND_ERR?n():b()}))}),b)}),b)):void b())},m=y.prototype,S=function(e,t,n){return new y(e,t,n)};return"undefined"!=typeof navigator&&navigator.msSaveOrOpenBlob?function(e,t,n){return n||(e=w(e)),navigator.msSaveOrOpenBlob(e,t||"download")}:(m.abort=function(){var e=this;e.readyState=e.DONE,p(e,"abort")},m.readyState=m.INIT=0,m.WRITING=1,m.DONE=2,m.error=m.onwritestart=m.onprogress=m.onwrite=m.onabort=m.onerror=m.onwriteend=null,S)}}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||this.content);"undefined"!=typeof module&&module.exports?module.exports.saveAs=saveAs:"undefined"!=typeof define&&null!==define&&null!==define.amd&&define([],function(){return saveAs});
wordexport.js takes advantage of Word's ability to render HTML content in a .doc file. So the answer is the same as if you were adding an image to an HTML document: the img tag:
...
var static = {
mhtml: {
top: "Mime-Version: 1.0\nContent-Base: " + location.href + "\nContent-Type: Multipart/related; boundary=\"NEXT.ITEM-BOUNDARY\";type=\"text/html\"\n\n--NEXT.ITEM-BOUNDARY\nContent-Type: text/html; charset=\"utf-8\"\nContent-Location: " + location.href + "\n\n<!DOCTYPE html>\n<html>\n_html_</html>",
head: "<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n<style>\n_styles_\n</style>\n</head>\n",
body: "<body><img src="http://www.example.com/media/examples/frog.png" alt="Frog"/>_body_</body>"
}
};
...
According to this page, setting the mso-element style appropriately can be used to specify headers and footers. Without fully trying it out, you may also have to treat the header/footer as a separate file (which gets combined in the 'Aggregate parts of the file together' part):
<div style="mso-element:header;" id="h1">
<img src="http://www.example.com/media/examples/frog.png" alt="Frog"/>
</div>
<div style='mso-element:footer' id=f1>
<img src="http://www.example.com/media/examples/frog.png" alt="Frog"/>
</div>

I have a slideshow working to change the images, however how do i add a seperate html page link to each image

var index=0;
var titles=[1,2,3,4];
function moveToNextSlide()
{
if (index >= 4){index=0}
var img = document.getElementById("img1");
var slideName="images/img" + titles[++index] + ".jpg";
img.src=slideName;
}
function moveToPreviousSlide()
{
if (index <= 0){index=4}
{
var img = document.getElementById("img1");
var slideName="images/img" + titles[--index] + ".jpg";
img.src=slideName;
}
}
That is the javascript code for my slideshow and in my html I have used input buttons next and back to call the image change.
How do I add a random html link so when I click on a image it goes to a different html page?
Surround your <img> tag inside an <a> like this:
<img id="img1" src="images/img1.jpg">
Now in both the methods add code to update the href of the tag accordingly.
var urls=["http://www.example.com","http://www.example2.com","http://www.example3.com","http://www.example4.com"];
function moveToNextSlide()
{
if (index >= 4){index=0}
var img = document.getElementById("img1");
var slideName="images/img" + titles[++index] + ".jpg";
img.src=slideName;
var link= document.getElementById("link1");
var url=urls[++index];
link.href=url;
}
function moveToPreviousSlide()
{
if (index <= 0){index=4}
{
var img = document.getElementById("img1");
var slideName="images/img" + titles[--index] + ".jpg";
img.src=slideName;
var link= document.getElementById("link1");
var url=urls[++index];
link.href=url;
}
}
Try and tell.

Searching an external URL for files with javascript

I am building a page that needs to be able to get a all the file links on a webpage and add them to a dropdown list. Original it was the script was supposed to be on the same page as the files but now it needs to search an external. This is what I used before the change
<script>
$(document).ready(function() {
var arr = [];
var filenames = [];
var alt_var;
var baseURL = "www.fakeurl.com"
$('.ms-vb-icon').find('a').each(function(){
var temp = $(this).attr('href')
$(this).find('img').each(function(){
alt_var = $(this).attr('alt');
});
if(temp.indexOf('.csv') != -1){arr.push(temp); filenames.push(alt_var);}
});
for(i = 0; i < arr.length; ++i)
{
var x = document.createElement('li');
var a = document.createElement('a');
var t = document.createTextNode(" " + filenames[i]);
var fullURL = baseURL + arr[i];
a.setAttribute('href',"#");
a.setAttribute('class', "glyphicon glyphicon-file");
a.setAttribute('id', baseURL + arr[i]);
a.setAttribute('onclick', "drawChart(this.id)");
a.appendChild(t);
x.appendChild(a);
document.getElementById("dropdownfiles").appendChild(x);
}
});
</script>
How can I change this to search an external url. (PS new to Javascript)
Not sure if this is the cleanest way but you could add a hidden iframe on the page and then search in there.
css:
.externalSearcher iframe {
display: none;
}
html:
<div class="externalSearcher"></div>
js:
$('.externalSearcher').append('<iframe src="' + externalLink + '"></iframe>');
$('.externalSearcher').find('a').each(function () {
//do what you want with the link
});

Changing current attribute of HTML,from where the function gets called

I am using JavaScript to build a dynamic HTML page, here is my code:
for (var i = 0; i < getImage.length; i++) {
$("#a1").append("<img src=\"" + getImage(images[i])+" \"width=\"90\"");
}
The getImage function returns an image...My question, how can I with JavaScript or Jquery in each iteration change the attribute of that current line, for example changing width or any image attribute of that current line in my getImage function . If I use $('this') it returns the object, but not in reference to that current line. Can I change those things in every iteration inside that function? so as a result I would get:
<img src="1.jpg" width="20">
<img src="2.jpg" width="90" >
function getImage(i) {
// some code
// WANT TO CHANGE HERE THE IMG ATTRIBUTE OF <img src "" width="">
return image ;
}
The idea of course is to change many more attributes...
If you want to be able to change the image attributes from within getImage then you should not use string-concatenation to build the image-tag.
Try something like:
for (var i = 0; i < images.length; i++) {
$("#a1").append(getImage(images[i]));
}
with:
function getImage(input) {
var $img = $('<img>').attr({
src: '%your-source%', // maybe from input?!
width: 100
});
// do other stuff with $img as needed
return $img;
}
You can't do that as you have it now. As far as I understand, getImage simply returns an URL to an image. And it can't modify width of img tag. You can do it like that:
for (var i = 0; i < getImage.length; i++) {
$("#a1").append("<img src=\"" + getImage(images[i]) + " \"width=\"" + images[i].width + "\"");
}
assuming that your images array contains objects with fields src and width
Or you should make your getImage return whole img tag HTML:
for (var i = 0; i < getImage.length; i++) {
$("#a1").append(getImage(images[i]));
}
function getImage(index) {
// some code
return "<img src=\"" + image + " \"width=\"" + width + "\"";
}
This may have some mistakes but i just want to share an idea of how you could do this in another way.
for (var i = 0; i < getImage.length; i++) {
$("#a1").append(getImage(images[i]));
}
function getImage(i) {
var s = // get the src
var w = // width based on i
return "<img src=\"" + s+ " \"width=\"" + w+ "\"" ;
}

How to check if the image is loaded?

with ajax i get an array of pictures URL and then I need to create from them the gallery. I also need to make a counter that shows the number of downloaded images, it looks like this:
var images;
var load_image = new Image();
load_image.onload = function(){
myPhotoSwipe.show(0);
}
$.each(images['images'], function(key, value) {
load_image.src = ('index.php?load_image=' + value);
$('#image_count').remove();
$('span[class="loading"]').after('<div id="count"><h6>Images: ['+key+' / '+images_array['images'].length+']</h6></div>');
images+= '<li><img src="index.php?load_image='+value+'" /></li>';
});
The problem is that the counter is always loaded at penultimate element and stay there until all images are loaded, but I need to show the load of each like a progress.
P.S.
I also tried complete, but it didn't help.
This should fix it. The reason is because the load handler was being bound to only 1 image object.
var images;
$.each(images['images'], function(key, value) {
var load_image = new Image();
load_image.src = ('index.php?load_image=' + value);
$('#image_count').remove();
$('span[class="loading"]').after('<div id="count"><h6>Images: ['+key+' / '+images_array['images'].length+']</h6></div>');
images+= '<li><img src="index.php?load_image='+value+'" /></li>';
load_image.onload = function(){
myPhotoSwipe.show(0);
}
});
You are almost there.
The problem is that you are re-using the same image object. You need to create an array of load_image instances and increment your counter inside onload, when each of them returns.
function load(){
var imageUrls = [];
imageUrls.push('http://www.nasa.gov/images/content/690106main_iss033e005644_full.jpg');
imageUrls.push('http://www.nasa.gov/images/content/690669main_201209210010_full.jpg');
imageUrls.push('http://www.nasa.gov/images/content/691806main_hs3_full_full.jpg');
imageUrls.push('http://www.nasa.gov/images/content/689231main_Webb_Mirror_Cans_orig_full.jpg');
var images = [];
var i;
var counter = 0;
var mainDiv = document.getElementById('somediv');
var counterDiv = document.getElementById('counter');
for (i = 0; i < imageUrls.length; i++)
{
images[i] = new Image();
images[i].width = 100;
images[i].height = 100;
images[i].onload = function () {
counter++;
counterDiv.innerText = counter;
}
mainDiv.appendChild(images[i]);
images[i].src = imageUrls[i];
}
}

Categories

Resources