Store local image to upload in another page [duplicate] - javascript

This question already has answers here:
How to save an image to localStorage and display it on the next page?
(8 answers)
Closed 6 years ago.
I have to make an image input that will not upload the image. The images will be used in another page where it will be edited(cropped and draw over) and then uploaded.
I don't know how to do that, do you have any ideas? I'll probably be using this plugin.

you have get the image using getElementByID. convert the image in to base64 and save in local storage
userimage = document.getElementById('imageId');
imageData = getBase64Image(userimage);
localStorage.setItem("imageData", imageData);
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
insert the script in your second page for getting the image from localstorage and set to the image src
window.onload = function() {
var getpicture = localStorage.getItem('imageData');
var image = document.createElement('img');
image.src = getpicture;
};

Related

create image data in javascript

I want to create a black (or white, I really don't care the "colour") 1x1px image in javascript, I tried doing it with var img = new Image(1,1) but I don't know how assigng the source of the image with img.src to be all black (I don't want to use a file, I want to be generated with JS code).
There is a way to do that?
You can also use base64 encoded data in the image.src.
var image = new Image(10, 10);
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=";
document.body.appendChild(image);
I found it:
var image = document.createElement('canvas').getContext('2d').getImageData(0,0,1,1);
I'll let question open to know if there is another way to do it.
Sources I used:
CanvasRenderingContext2D.createImageData()
CanvasRenderingContext2D.getImageData()
Similarly you can perform the image manipulation in canvas, then pass a data URI containing a representation of the image over to the HTML image for actual rendering.
const imgWidth = 1;
const canvas = document.createElement("canvas");
canvas.width = imgWidth;
canvas.height = imgWidth;
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'black';
ctx.fillRect(0,0,imgWidth,imgWidth);
const url = canvas.toDataURL();
const newImg = document.createElement("img");
newImg.src = url;
document.body.insertBefore(newImg, null);

How to convert live image url into blob in angular? [duplicate]

This question already has answers here:
DOMException when playing audio with blob as source
(2 answers)
How to get the image size (height & width) using JavaScript
(33 answers)
Getting BLOB data from XHR request
(4 answers)
Closed 3 years ago.
Im working in angular 7 and my requirement is i need to get Width, Height and Size (in how much kb or mb) of the image and also im trying to convert it into blob.
I tried with below code but im not getting exact output:
var img_url = "http://snook.ca/files/mootools_83_snookca.png";
var blob = new Blob([img_url]);
let reader = new FileReader;
reader.readAsDataURL(blob); // read file as data url
reader.onload = () => { // when file has loaded
console.log(reader.result)
var img:any = new Image();
img.src = reader.result;
img.onload = () => {
this.uploaded_image_width = img.width; //to get image width
this.uploaded_image_height = img.height; //to get image height
this.uploaded_image_url = reader.result; //to get blob image
console.log(reader.result)
};
}
When im consoling the blob data is coming wrong (console.log(reader.result)) and inside img.onload function is not executing.
I referred this fiddle to achieve this :
http://jsfiddle.net/guest271314/9mg5sf7o/
you can try like this way. i hope it helps you out
var img = new Image();
img.onload = function(){
alert( this.width+' '+ this.height );
};
img.src = "http://lorempixel.com/output/city-q-c-250-250-1.jpg";

Get width and height of an image loaded via a FileReader [duplicate]

This question already has answers here:
Get image width and height from the Base64 code in JavaScript
(5 answers)
How to get the image size (height & width) using JavaScript
(33 answers)
Closed 8 years ago.
I have an image that is created via a FileReader:
var fileReader = new FileReader();
var deferred = $.Deferred();
fileReader.onload = function(event) {
deferred.resolve(event.target.result);
};
fileReader.onerror = function() {
deferred.reject(this);
};
fileReader.readAsDataURL(file);
return deferred.promise();
This returns a base64 encoded string which I use with:
var img = $('<img src="' + fileB64 + '">');
Then this is added to my page.
I wish to get the original height and width of that image.
I can get the size of it on the page via:
this.img = img;
this.imgWidth = this.img.width();
this.imgHeight = this.img.height();
But I wish to get its original width and height.
I think the only way you can determine the image's width and height is to actually create an image element and then get the dimensions from that:
var img = new Image();
img.src = fileB64;
var width = img.width;
var height = img.height;
I'm assuming (i.e. I haven't checked) that loading a data: URL into an image's src property will cause it to load synchronously. Use img.onload otherwise.
Having created the element off-screen like this, you can then add the very same element into the page.

How convert downloaded inline image into Base64 on client side

Is there any technique to convert images that have already been downloaded – inline JPEG/GIF/etc. images that occur in a webpage – into Base64 data using client-side JavaScript?
I am not talking about how to transform an image into Base64 using other means (server-side, online tools, etc.).
These are the constraints for my particular use case:
The image is on screen now, right in the page, in front of person. It has already been downloaded in a data sense.
The conversion from raw image data has to be done client-side.
The images in question are from arbitrary domains. That is, they may or may not, be of same origin domain.
The user, if needed (if helpful to solution), can give additional permissions (for example, a FF toolbar install to help skirt cross-domain and other issues). That is, code can be given special endorsement on the client side if that helps solve the issue.
The end goal is to transform all images on the page (in the DOM) into Base64 data inside of JavaScript. Put another way, every image the user can see on the page has been converted into a JavaScript variable of some sort that contains the Base64 data.
So far I see no posts that stay inside of all the above constraints.
I think this is close to what you are looking for but the only problem is that it only works for locally hosted images and HTML5 only.
function toURL(image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext("2d");
context.drawImage(image, 0, 0);
var s = canvas.toDataURL();
return s.substring(s.indexOf(","));
}
var test = document.getElementById("myImage");
console.log(toURL(test));
You can trick javascript into thinking an image is from your domain with the following code.
image.php
<?php
$image = getAnImagePathAndTypeFromTheDatabaseByID($_GET["id"]);
//returns something like
//array("path" => "http://www.anotherwebsite.com/image.png", "type" => "png")
header("Content-type: image/$image[type]");
echo file_get_contents($image["path"]);
?>
Then just navigate to image.php?id=1 for example.
For it to work in cross-domain client-side you need to call the image with the attribute crossorigin = "true", or, add a line in the Logan Murphy code:
function toURL(image) {
image.setAttribute('crossOrigin', 'anonymous');
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext("2d");
context.drawImage(image, 0, 0);
var s = canvas.toDataURL();
return s.substring(s.indexOf(","));
}
I use this code:
// image-to-uri.js v1
// converts a URL of an image into a dataURI
function imageToURI(url, callback) {
// Create an empty canvas and image elements
let canvas = document.createElement('canvas');
let img = document.createElement('img');
img.onload = function () {
let ctx = canvas.getContext('2d');
// match size of image
canvas.width = img.naturalWidth || img.width;
canvas.height = img.naturalHeight || img.height;
// Copy the image contents to the canvas
ctx.drawImage(img, 0, 0);
// Get the data-URI formatted image
callback(null, canvas.toDataURL('image/png'));
};
img.ononerror = function () {
callback(new Error('FailedToLoadImage'));
};
// canvas is not supported
if (!canvas.getContext) {
setTimeout(callback, 0, new Error('CanvasIsNotSupported'));
} else {
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
};
};
which is based on this https://github.com/HenrikJoreteg/image-to-data-uri.js/blob/master/image-to-data-uri.js

Restore canvas with base64 string

Whenever i first loaded the page. The image doesn't get restored but once i load the page and i hit F5. then it works. i'm not where whats wrong with my code.
// variable r contains the base64 string which is retrieved via a ajax call.
var myImage = new Image();
myImage.src = r;
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.drawImage(myImage, 0, 0);
Ok. Instead of calling the ajax automatically when the page is loaded, i manually triggered the ajax call via a button, still i get the same result.
The base64 strings is retrieved successfully and imaged is not loaded. but when i clicked the button for a second time. the image is than loaded.
var myImage = new Image();
myImage.src = r;
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
// wait for it to load before calling draw
myImage.onload = function() {
ctx.drawImage(myImage, 0, 0);
}

Categories

Resources