9

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/

VinoCoder
  • 1,133
  • 5
  • 22
  • 45
  • which version of angular you are using? – TheParam Apr 05 '19 at 08:39
  • You have to set the source of your image to load it. `onload` is called only when the image has a src. The issue here is that you have set the source BEFORE declaring the hook : move the line BELOW the hook, and you should be fine ! –  Apr 05 '19 at 08:48
  • That was for Audio rather than Image, but really it's just the same. – Kaiido Apr 05 '19 at 09:14
  • Im using Angular 7 @TheParam – VinoCoder Apr 05 '19 at 09:25
  • Please see my question clearly it's not same @Kaiido – VinoCoder Apr 05 '19 at 09:41
  • The problem for me is the image is not in my local or uploaded one it's in live @Kaiido – VinoCoder Apr 05 '19 at 10:01
  • The problem is that you are asking 3 questions in a single one... To get a Blob from this URL would require that the target server allows you to perform ajax requests, then that's just a matter of fetch(url).then(r=>r.blob) I added yet another link about this part of your question, but once again for it to succeed the target server must allow you. – Kaiido Apr 05 '19 at 10:03

1 Answers1

1

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";
Yash Rami
  • 2,276
  • 1
  • 10
  • 16