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

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";

Related

How to get user selected image height and width in react js [duplicate]

I require to generate a thumbnail of an image in my web application. I make use of the HTML5 File API to generate the thumbnail.
I made use of the examples from Read files in JavaScript to generate the thumbnails.
I am successfully able to generate the thumbnails, but I am able to generate thumbnail only by using a static size. Is there a way to get the file dimensions from the selected file and then create the Image object?
Yes, read the file as a data URL and pass that data URL to the src of an Image: http://jsfiddle.net/pimvdb/eD2Ez/2/.
var fr = new FileReader;
fr.onload = function() { // file is loaded
var img = new Image;
img.onload = function() {
alert(img.width); // image is loaded; sizes are available
};
img.src = fr.result; // is the data URL because called with readAsDataURL
};
fr.readAsDataURL(this.files[0]); // I'm using a <input type="file"> for demonstrating
Or use an object URL: http://jsfiddle.net/8C4UB/
var url = URL.createObjectURL(this.files[0]);
var img = new Image;
img.onload = function() {
alert(img.width);
URL.revokeObjectURL(img.src);
};
img.src = url;
The existing answers helped me a lot. However, the odd order of events due to the img.onload event made things a little messy for me. So I adjusted the existing solutions and combined them with a promise-based approach.
Here is a function returning a promise with the dimensions as an object:
const getHeightAndWidthFromDataUrl = dataURL => new Promise(resolve => {
const img = new Image()
img.onload = () => {
resolve({
height: img.height,
width: img.width
})
}
img.src = dataURL
})
Here is how you could use it with an async function:
// Get a file from an input field
const file = document.querySelector('[type="file"]').files[0]
// Get the data URL of the image as a string
const fileAsDataURL = window.URL.createObjectURL(file)
// Get dimensions
const someFunction = async () => {
const dimensions = await getHeightAndWidthFromDataUrl(fileAsDataURL)
// Do something with dimensions ...
}
And here is how you could use it using the then() syntax:
// Get a file from an input field
const file = document.querySelector('[type="file"]').files[0]
// Get the data URL of the image as a string
const fileAsDataURL = window.URL.createObjectURL(file)
// Get the dimensions
getHeightAndWidthFromDataUrl(fileAsDataURL).then(dimensions => {
// Do something with dimensions
})
I have wrapped pimvdb's answer in a function for general-purpose use in my project:
function checkImageSize(image, minW, minH, maxW, maxH, cbOK, cbKO) {
// Check whether browser fully supports all File API
if (window.File && window.FileReader && window.FileList && window.Blob) {
var fr = new FileReader;
fr.onload = function() { // File is loaded
var img = new Image;
img.onload = function() { // The image is loaded; sizes are available
if(img.width < minW || img.height < minH || img.width > maxW || img.height > maxH) {
cbKO();
} else {
cbOK();
}
};
img.src = fr.result; // Is the data URL because called with readAsDataURL
};
fr.readAsDataURL(image.files[0]);
} else {
alert("Please upgrade your browser, because your current browser lacks some new features we need!");
}
}

Javascript Convert a URL to a base64 Image [duplicate]

This question already has answers here:
canvas.toDataURL() SecurityError
(8 answers)
Closed 6 years ago.
I am trying to convert an image url to a base64 image. I have found this which I am trying to make use of.
I have the following code:
var imgUrl = 'https://www.google.de/images/srpr/logo11w.png';
let base64image = this.getBase64Image(imgUrl);
console.log(base64image);
and
public getBase64Image(imgUrl) {
var img = new Image();
img.src = imgUrl;
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,/, "");
}
But, it outputs the following:
data:,
I get the following error in the console:
EXCEPTION: Uncaught (in promise): SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
Error: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
My code must me incoreect. Can anyone please advise how to convert the url to a base64 image?
Thanks
UPDATE
I aded the following line to the function:
img.crossOrigin = "Anonymous";
That got rid of the error, however, now I get the following:
data:,
You can use an XHR and the File Reader API instead, which is cleaner but is limited in browser compatibility.
var imgxhr = new XMLHttpRequest();
imgxhr.open( "GET", url );
imgxhr.responseType = "blob";
imgxhr.onload = function (){
if ( imgxhr.status===200 ){
reader.readAsDataURL(imgxhr.response);
}
else if ( imgxhr.status===404 ){
// Error handle
}
};
var reader = new FileReader();
reader.onloadend = function () {
console.log(reader.result.length);
// Code here
};
imgxhr.send();

Store local image to upload in another page [duplicate]

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;
};

PNG or JPG (not rgb) over websocket with ArrayBuffer without base64

Is there a way to render a PNG image to canvas without having to encode it to base64?
Server sends a PNG in binary, client receives it in an ArrayBuffer
and displays it on the canvas. Only way I could get this to work is by encoding the data to base64 - on the server side - as I need it to be fast. On the client side, I created an image obj with data:image/png;base64 tag.
I know you can create a blob and a file reader but I could not get that to work.
This is the blob version:
var blob = new Blob([image.buffer],{type: "image/png"});
var imgReader = new FileReader();
imgReader.onload = function (e) {
var img = new Image();
img.onload = function (e) {
console.log("PNG Loaded");
ctx.drawImage(img, left, top);
window.URL.revokeObjectURL(img.src);
img = null;
};
img.onerror = img.onabort = function () {
img = null;
};
img.src = e.target.result;
imgReader = null;
}
imgReader.readAsDataURL(blob);
image is Uint8Array. I create a blob from it. The rest is self-explanatory.
Images are correct and valid PNG images. When I send it from the server, I wrote them to a file on the server side and they render fine with an image viewer.
You can create a blob url with createObjectURL without having to do any base64 encoding, just pass the blob you crated to it and you will have a url you can set as img.src
var blob = new Blob([image],{type: "image/png"});
var img = new Image();
img.onload = function (e) {
console.log("PNG Loaded");
ctx.drawImage(img, left, top);
window.URL.revokeObjectURL(img.src);
img = null;
};
img.onerror = img.onabort = function () {
img = null;
};
img.src = window.URL.createObjectURL(blob);
I've only seen it used in this way. If you don't want to send the base64 via the network, then, you can use the btoa to convert the binary data to a base64 on the client side.
Looking at MDN, drawImage takes a CanvasImageSource object. CanvasImageSource represents any object of type HTMLImageElement, ImageBitmap and few others.
On further searching, I found some information related to ImageBitmap, but, not enough to provide a solution.
I could have added this to the comment, but, it would have become a massive comment and lose all the clarity.

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.

Categories

Resources