I want to access the local resources/files which are stored in the web browser when are on a web site. I am trying to generate a dataURI for the images which are loaded whenever we visit a site using JS and print the same in the console log.
NOTE: The image is being downloaded from a remote server and is not stored locally.
Any suggestions/methods to accomplish this? Any method to directly gain access to the .jpeg, .png, etc from the browser resources?
Heres the code of sample website i am trying this on
<html>
<head>
<title>Image_split</title>
</head>
<body>
<h1>Splitting images within the browser</h1>
<br><hr><br>
<img src="https://www.google.co.in/images/srpr/logo11w.png" />
<br><hr><br>
<p id="split_result"></p>
<br><hr><br>
<script src="image_split.js"></script>
</body>
Here is the JS
var image_elements = document.getElementsByTagName("img");
var i;
var count=0;
for(i=0;i<image_elements.length; i++){
count++;
}
var image = image_elements[0];
/*if(count>0){
document.getElementById("split_result").innerHTML = image_elements[0];
}*/
//The code below does not work :(
/*
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 100, 100);
document.getElementById("split_result").innerHTML = canvas.toDataURL("image/png");
*/
I want to access the image stored at image_elements[0] directly from local cache and modify the same with JS.
![link to image]https://drive.google.com/file/d/0B7UeFzC7IXYaODN0SWhGZlp2dnc/view?usp=sharing
Thanks :)
Heres the solution code to access images from web browser resources without getting 'HTMLCanvasElement': Tainted canvases may not be exported.'
var image_elements = document.getElementsByTagName("img");
var i;
var count=0;
for(i=0;i<image_elements.length; i++){
count++;
}
var image = image_elements[0];
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt){
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
//canvas.getContext("2d").drawImage(image, 0, 0);
var dataModel = canvas.getContext("2d").getImageData(0, 0, image.width, image.height);
document.getElementById("split_result").innerHTML = dataModel.data.byteLength;
}
Related
I'm trying to get a base64 version of a canvas in HTML5.
Currently, the base64 image that I get from the canvas is blank.
I have found similar questions for example this one:
HTML Canvas image to Base64 problem
However, the issue that I have is that because I am adding 2 images in the canvas, I cannot use the example provided in those answers as most of them are using single image.
I understand that I have to wait until the canvas image is loaded properly before trying to get the base64 image. But I don't know how in my case.
This is my code:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.canvas.width = 1000;
context.canvas.height = 1000;
var imageObj1 = new Image();
imageObj1.src = "http://www.offthegridnews.com/wp-content/uploads/2017/01/selfie-psuDOTedu.jpg";
imageObj1.onload = function() {
context.drawImage(imageObj1, 0, 180, canvas.width, canvas.height);
};
var imageObj2 = new Image();
imageObj2.src = "http://www.publicdomainpictures.net/pictures/150000/velka/banner-header-tapete-145002399028x.jpg"
imageObj2.onload = function() {
context.drawImage(imageObj2, 0, 0, canvas.width, 180);
};
// get png data url
//var pngUrl = canvas.toDataURL();
var pngUrl = canvas.toDataURL('image/png');
// get jpeg data url
var jpegUrl = canvas.toDataURL('image/jpeg');
$('#base').val(pngUrl);
<div class="contents" style="overflow-x:hidden; overflow-y:scroll;">
<div style="width:100%; height:90%;">
<canvas id="myCanvas" class="snap" style="width:100%; height:100%;" onclick="takephoto()"></canvas>
</div>
</div>
<p>
This is the base64 image
</p>
<textarea id="base">
</textarea>
and this is a working FIDDLE:
https://jsfiddle.net/3p3e6Ldu/1/
Can someone please advice on this issue?
Thanks in advance.
EDIT:
As suggested in the comments bellow, i tried to use a counter and when the counter reaches a specific number, I convert the canvas to base64.
Like so:https://jsfiddle.net/3p3e6Ldu/4/
In both your examples (the one from the question and the one from the comments), the order of commands does not really respect the async nature of the task at hand.
In your later example, you should put the if( count == 2 ) block inside the onload callbacks to make it work.
However, even then you will run into the next problem: You are loading the images from different domains. You can still draw them (either into the canvas or using an <img> tag), but you are not able to access their contents directly. Not even with the detour of using the <canvas> element.
I changed to code so it would work, if the images are hosted on the same domain. I also used a function to load the image and promises to handle the callbacks. The direct way of using callbacks and a counting variable, seem error-prone to me. If you check out the respective fiddle, you will notice the SecurityError shown. This is the result of the aforementioned problem with the Same-Origin-Policy I mentioned.
A previous question of mine in a similar direction was about how to detect, if I can still read the contents of a <canvas> after adding some images.
const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
context.canvas.width = 1000;
context.canvas.height = 1000;
// function to retrieve an image
function loadImage(url) {
return new Promise((fulfill, reject) => {
let imageObj = new Image();
imageObj.onload = () => fulfill(imageObj);
imageObj.src = url;
});
}
// get images
Promise.all([
loadImage("http://www.offthegridnews.com/wp-content/uploads/2017/01/selfie-psuDOTedu.jpg"),
loadImage("http://www.publicdomainpictures.net/pictures/150000/velka/banner-header-tapete-145002399028x.jpg"),
])
.then((images) => {
// draw images to canvas
context.drawImage(images[0], 0, 180, canvas.width, canvas.height);
context.drawImage(images[1], 0, 0, canvas.width, 180);
// export to png/jpg
const pngUrl = canvas.toDataURL('image/png');
const jpegUrl = canvas.toDataURL('image/jpeg');
// show in textarea
$('#base').val(pngUrl);
})
.catch( (e) => alert(e) );
I am using Mozilla pdf js in meteor. The package I am using is from "https://atmospherejs.com/pascoual/pdfjs"
I am doing almost everything that they have stated in their example, but my pdf file is delivered as a image file. It is not getting displayed as shown in their example "https://mozilla.github.io/pdf.js/web/viewer.html".
Please let me know what have I done wrong. My code is as follows:
<template name="displayResume">
<canvas id="pdfcanvas"></canvas>
</template>
Template.displayResume.rendered = function(){
PDFJS.workerSrc = '/packages/pascoual_pdfjs/build/pdf.worker.js';
console.log(PDFJS)
//PDFJS.workerSrc = '/.meteor/local/build/programs/web.browser/packages/pascoual_pdfjs/build/pdf.worker.js';
var url = '/Lez6dci9xoaiyWuzR.pdf';
PDFJS.getDocument(url).then(function getPdfHelloWorld(pdf) {
// Fetch the first page
pdf.getPage(1).then(function getPageHelloWorld(page) {
var scale = 1;
var viewport = page.getViewport(scale);
// Prepare canvas using PDF page dimensions
var canvas = document.getElementById('pdfcanvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
page.render({canvasContext: context, viewport: viewport}).promise.then(function () {
console.log('rendered');
});
});
});
}
I am just trying to display resume from my public folder as of now. Later, I will have to display file from amazon aws.
Thanks in advance
they had a pageviewer example here:
https://github.com/mozilla/pdf.js/blob/master/examples/components/pageviewer.js
I think the line you are looking for is:
textLayerFactory: new PDFJS.DefaultTextLayerFactory(),
The webpage is being run on Safari on an iPad.
I have a canvas with the id "canvas1div". I would like to be able to receive this canvas as an image either by email or directly into the photo library.
Via Photo Library
With regards to the photo library, I found this question
Save canvas image on local mobile storage for IOS/Android
This is the function that I would like to call to save the image
function saveimage() {
window.canvas2ImagePlugin.saveImageDataToLibrary(
document.getElementById('canvas1div')
);
}
I don't know how to manually add the plug in to javascript so any advice here would be greatly appreciated.
Email
Again I don't know how to convert the canvas to an image and email it.
Thank you for your help
Don't know if this helps you but here you can find download but email send from JavaScript with email cannot be done:
Example with download file below http://jsfiddle.net/oa2s5eu7/1/
Javscript:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,150,75);
// Converts image to canvas; returns new canvas element
function convertImageToCanvas(image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0);
return canvas;
}
// Converts canvas to an image
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
}
document.getElementById('mydownload').onclick= function(){
var image = convertCanvasToImage(document.getElementById("myCanvas"));
var anchor = document.createElement('a');
console.log(anchor);
anchor.setAttribute('href', image.src);
anchor.setAttribute('download', 'image.png');
anchor.click();
}
document.getElementById('sendEmail').onclick= function(){
var image = convertCanvasToImage(document.getElementById("myCanvas"));
window.open('mailto:test#example.com?subject=subject&body=you cann send only txt from javscript in email ', '_blank');
}
Html:
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<button id='mydownload'>Download Image</button>
<button id='sendEmail'>Send Email</button>
I need to write a new HTML file from a string using file system, I'm using Cordova 2.4.0. . That HTML would have some images loaded from a local folder, so because I need just one file (a HTML without png/jpg images alongside it) I'm trying to encode this images and apply them through CSS as background images (The CSS code is embeded in the same String, future HTML file). Well, the way I make these modifications to the string is by using functions returns. For example:
padding-top: 5%; background-image: url(' + agregaImagenLocal('../img/ESTELAR.png') + '); background-color: white;
The function "agregaImagenLocal(pathToLocalImage)" :
function agregaImagenLocal(pathToLocalFile) {
var canvas = document.getElementById('canvasOculto');
var imagen = new Image(150,100);
canvas.width = imagen.width;
canvas.height = imagen.height;
var contextoCanvas = canvas.getContext('2d');
imagen.onload = function () {
contextoCanvas.drawImage(imagen, 0, 0);
urlImagenLocal = canvas.toDataURL();
}
imagen.src = pathToLocalFile;
return urlImagenLocal //???????
}
I was doing this without the "onload" event, so it returned a blank image. But with this function inside the "onload" I don't know how to return the base64 encoded image to the first function.
This is the function to convert an Image (by file path) to Base64:
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;
}
Once the conversion is made, you can use jQuery to set the background CSS using the Base64 code.
var imageUrl = ""; //Your Local Image Path HERE
convertImgToBase64(imageUrl, function(base64Img){
$('.output').css("background-image", base64Img);
}
This will set the source of an element with the class 'output' to the base64 image.
I'm really struggling to write a function for getting the Base64 encoding of an image. Since this function will be part of a bigger script that uses jsPDF.js to make PDFs on-the-fly from a website, It's important the be able to calculate those Base64 encodings as the result of a function. The images will be hosted on the same server, so no same-origin issues. I know the .toDataURL() method of the canvas element can do this and I also know that the image needs to be fully loaded in order to get the Data URL correctly, so I wrote this function
// Encode image to Base64
function encodeBase64(url, format)
{
var image = new Image(),
canvas = document.createElement("canvas"),
context = canvas.getContext("2d");
image.src = url;
image.onload = function ()
{
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0, image.width, image.height);
var dataURL = canvas.toDataURL(format);
alert(dataURL);
};
}
The problem is that I don't know how to "extract" the dataURL value from the onload function so that the encodeBase64 function simply returns that value and I can put it in an array. Alert returns that string correctly so I'm sure the code works, but if I try to write any other statement like "return dataURL" or similar I just get undefined value. Please help.
First load all the images into an array.
Then create the dataURLs using canvas and load the dataURLs into a second array.
Example code and a Demo: http://jsfiddle.net/m1erickson/fbdb3qbw/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// array for dataURLs
var dataURLs=[];
// put the paths to your images in imageURLs[]
var imageURLs=[];
// push all your image urls!
imageURLs.push({url:"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/sun.png",format:null});
imageURLs.push({url:"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/temp1.png",format:'image/jpeg'});
// the loaded images will be placed in images[]
var imgs=[];
var imagesOK=0;
loadAllImages(start);
function loadAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
img.format=imageURLs[i].format;
imgs.push(img);
dataURLs.push('');
img.index=imgs.length-1;
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i].url;
}
}
function start(){
// the imgs[] array now holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
// now loop through each img and create its dataURL
for(var i=0;i<imgs.length;i++){
var img=imgs[i];
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
dataURLs[img.index] = canvas.toDataURL(img.format);
}
// Demo: report the results to the console
console.log(dataURLs);
}
}); // end $(function(){});
</script>
</head>
<body>
<h4>Fetch dataURLs from images (see results in the console)</h4>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
[ Addition: pulling urls from textarea ]
Here's how to pull the urls from the textarea.
(#loadImages is a button that's pushed when your user has typed the urls into the textbox).
I haven't looked at the jsPDF source so I can't speak to your dims issue.
$('#loadImages').click(function(){
var inputText = document.getElementsByTagName("textarea")[0].value.split("\n");
for(var i = 0; i < inputText.length; i++){
imageURLs.push({url: inputText[i],format:"image/jpeg"});
}
loadAllImages(start);
});