I have a page with element
<input type="file" id="dialog-select-files" multiple="" accept="image/jpeg" name='files[]'>
After a user chooses files I want to load a new page with a gallery of selected photos.
So on my first page, I created URL, this way
URL.createObjectURL(files[i])
and saved it in cookies.
On my second page, I got URLs from cookies, created element 'img' and showed it on page:
var img = document.createElement("img");
img.src = getCookie(nameCookie);
gallery.appendChild(img);
But URL is blob URL, like
blob:http://localhost/8b67533a-f5f1-4529-8c3e-9829e6786be3 and it is not found on my second page.
How should I pass selected files from one page to another? I think I should use another way (not save in cookie), but I can't find a solution on the internet.
Thank you.
You can convert it to base64 string, then you can save it in the cookies or in the localStorage or in the sessionStorage and get it ftom there.
function img2base64(imgSrc, cb) {
var img = new Image();
// formats: image/png, image/jpeg, image/jpg, image/gif, image/bmp
var outputFormat = 'image/png';
img.onload = function() {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
cb(dataURL);
};
img.src = imgSrc;
}
var base64Str;
img2base64(imgSrc, function(dataUrl) {
// do something
console.log(dataUrl);
base64Str = dataUrl;
localStorage.setItem('img1', dataUrl);
});
Related
For some reason,I can't use any xhr request in my webview,so all the src of img can be loaded when I open the html, but if I want to save them to a pdf using something like jsPDF, all the img will be missing because of xhr request fail.So I want to ask is there any way to convert img src to base64 after page loaded without xhr request? And after page loaded,I think the images are already downloaded, so is it possible to find it locally and convert to base64 then set them back to src?
maybe use canvas to change srcs to base64?
const images = document.querySelectorAll("img");
images.forEach(img => {
img.onload = function() {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
const dataURL = canvas.toDataURL("image/jpeg");
img.setAttribute("src", dataURL);
};
});
I want to save an image of the canvas tag, but when i try create an image from the canvas it tells me "SecurityError: The operation is insecure", which i believe is problems with the canvas coming from another domain than what im on. This canvas is a map which is generated with openlayers3.
var canvas = document.getElementsByClassName('ol-unselectable')[0];
var dataURL = canvas.toDataURL('image/png');
var window = window.open();
window.document.write('<img src='+dataURL+'/>');
I've also tried
canvas.toBlob(function(blob) {
saveAs(blob, 'map.png')
}
Is there an easy work around so the canvas is not tainted?
You tried write in new browser window from another window this is impossible without https protocol or localhost. But you can create new img in currently window.
var canvas = document.getElementsByClassName('ol-unselectable')[0];
var dataURL = canvas.toDataURL('image/png');
var img = new Image();
img.width = 1000;
img.height = 1000;
img.src = dataURL;
img.onload = function () {
document.body.append(img);
}
I have a webpage with capture image from the Available camera feature. For the web version it simply places the video capture onto a canvas. However for a phone, I am using <input class="btn btn-info" type="file" accept="image/*" id="cameraCapture" capture="camera"> to capture a picture. It asks the user to either capture the image using the phone's camera or upload from its filesystem/gallery etc. Once the image is clicked it simply places the image's name next to the button.
Is there a way to access this image and display it in the same page.
Thanks in advance
You can do that with JS using FileReader object.
Take a look at this answer: preview-an-image-before-it-is-uploaded
I hope it helps
var input = document.querySelector('input[type=file]');
input.onchange = function () {
var file = input.files[0];
drawOnCanvas(file);
};
function drawOnCanvas(file) {
var reader = new FileReader();
reader.onload = function (e) {
var dataURL = e.target.result,
c = document.querySelector('canvas'),
ctx = c.getContext('2d'),
img = new Image();
img.onload = function() {
c.width = img.width;
c.height = img.height;
ctx.drawImage(img, 0, 0);
};
img.src = dataURL;
};
reader.readAsDataURL(file);
}
I want to create picture editor in js+jquery. At the first step i ask user to give image url. But I come across problem when i try load image data inside JS (to generate base64 image uri). I get error in console: … has beeb blocked by CORS policy: Access-Control-Allow-Origin …. But I wonder why? If in html file i create for instance (image hotlink):
<img src="https://static.pexels.com/photos/87293/pexels-photo-87293.jpeg" />
The browser load image without any CORS problems ! Here is my JS code which for the same image throw CORS problem:
function downloadFile(url) {
console.log({url});
var img = new Image();
img.onload = function() {
console.log('ok');
// never execute because cors error
// … make base64 uri with image data needed for further processing
};
img.crossOrigin = "Anonymous";
img.src = url;
}
So the question is - how to force JS to load image (as html-tag load it) and convert it to base64 url avoiding CORS problem?
https://static.pexels.com/photos/87293/pexels-photo-87293.jpeg
I try to found solution my self (JS ES6) but find only-partially. We are able to load img from no-CORS support src into canvas but browser switch cavnas into 'taint mode' which not allow us to call toDataURL (and any other access to content).
function loadImgAsBase64(url, callback) {
let canvas = document.createElement('CANVAS');
let img = document.createElement('img');
//img.setAttribute('crossorigin', 'anonymous');
img.src = url;
img.onload = () => {
canvas.height = img.height;
canvas.width = img.width;
let context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
let dataURL = canvas.toDataURL('image/png');
canvas = null;
callback(dataURL);
};
}
let url = 'http://lorempixel.com/500/150/sports/9/';
this.loadImgAsBase64(url, (dataURL) => {
msg.innerText = dataURL.slice(0,50)+'...';
});
IMAGE DATA: loading...<br>
<div id="msg"></div>
So only way to overcome this obstacle is to create proxy server (e.g. in PHP) which will have CORS 'on' and it will download images for given url and send back to our app in JS. I found some free server https://cors-anywhere.herokuapp.com which we can use to in development to tests. Below there is full functional code which return dataUri from given image url:
function loadImgAsBase64(url, callback) {
let canvas = document.createElement('CANVAS');
let img = document.createElement('img');
img.setAttribute('crossorigin', 'anonymous');
img.src = 'https://cors-anywhere.herokuapp.com/' + url;
img.onload = () => {
canvas.height = img.height;
canvas.width = img.width;
let context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
let dataURL = canvas.toDataURL('image/png');
canvas = null;
callback(dataURL);
};
}
let url = 'http://lorempixel.com/500/150/sports/9/';
this.loadImgAsBase64(url, (dataURL) => {
msg.innerText = dataURL.slice(0,50)+'...';
// show pic
document.body.innerHTML += `<img src="${dataURL}">`
});
IMAGE DATA Loading...<br>
<div id="msg"></div>
Thats all :) (I tested it on chrome, firefox and safari)
I had a similar issue and my issue was solved when I passed query parameter as part of the image url.
sample:
http://example.com/image.jpeg?test=123
The only way to avoid CORS is to make changes to avoid cross-origin sharing, at least let the browser thinks that it is cross-origin.
Or, you have to modify the server to support CORS.
I have a web page with file input field.I wanted to ,
Upload a image file.
create image element using uploaded image.
draw it on canvas
get "DataURL" of canvas.
This process works on Google Chrome,but not working on Mozilla Firefox.When i console.log the canvas.toDataURL output it shows
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABBoAAAJYCAYAAADMnIUCAAAJoUlEQVR4nO3BAQ0AAADCoPdPbQ8HFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8GeFIAAU/iP9QAAAAASUVORK5CYII=
This is not the correct output.How can i generate cross browser DataURL from the canvas.
Here is my code.
$scope.importImageForBackground = function (event)
{
$scope.file = event.target.files[0];
var img = document.createElement("img");
var reader = new FileReader();
reader.onloadend = function (e) {
$scope.$apply(function () {
img.src = e.target.result;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 1050;
canvas.height = 600;
ctx.drawImage(img, 0, 0, 1050, 600);
$scope.data = canvas.toDataURL("image/png");
console.log($scope.data);
});
};
reader.readAsDataURL($scope.file);
};
Wait for the image to load.
img.onload = function(){
var canvas = ...
};
img.src = e.target.result;
Please note that this is a copy-n-paste of #kaiido's comment, as he refused to repost it as an answer. Credit goes to him.
I faced the same issue, You can fix this using Javascript shown as below
var canvas=document.getElementById(canvasId);
var href=canvas.toDataURL("image/png");
var windowtab=window.open('about:blank','image from canvas');
windowtab.document.write("<img src='"+href+"' alt='from canvas'/>");