Home > OS >  How Can I Resize an Image In Angular Using the Canvas?
How Can I Resize an Image In Angular Using the Canvas?

Time:02-01

I am trying to resize a png that is received after clicking this button:

<input #FileInput id="fileControl" type="file" accept='image/*' (change)="addImage(FileInput.files, $event)">

After the button is clicked, it calls addImage and receives the file.

async addImage(files: any, event: any) {
    var dbKey = this.selectedHour;
    var length = this.detailsArray(this.selectedHour).length;
    if (files.length === 0) return;
    var mimeType = files[0].type;
    if (mimeType.match(/image\/*/) == null) { this.message = 'Only images are supported.';
        return;
    }
    var reader = new FileReader();
    for (let j = 0; j < files.length; j  ) {
        reader.readAsDataURL(files[j]);
        reader.onload = async (_event) => {
            var hour = this.selectedHour.slice(0, 4);
            var imgURL = reader.result;
            var resizedImage = '';
            await this.resizeImage(imgURL).then((resolve: any) => {
                resizedImage = resolve;
            });
            // keyparse works and give the right key
            let detailKey = this.keyParse(length.toString(), this.selectedHour.slice(0, 4));
            let caption = '';
            var theDict = {
                hour: hour,
                workHours: this.selectedHour,
                detailKey: detailKey,
                imgURL: resizedImage,
                caption: caption,
            };

           let hour = dict.workHours;
           let theArray = this.detailsControl.controls[hour] as FormArray;
           theArray.push(this.fb.group(dict));
        };
    }
...
}

Now I can add the image to the Form Group just fine, and it will display the image, but I need to have it resized:

resizeImage(imageURL: any): Promise<any> {
    return new Promise((resolve) => {
      var image = new Image();
      var what = '';
      image.onload = function () {
        var image = new Image();
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');

        if (ctx != null) {
          ctx.drawImage(image, 0, 0, 640, 480);
        }
        image.src;
        var data = canvas.toDataURL('image/png', 0.5);
        what = data;
        console.log('data', data);
      };
      image.src = imageURL;
      resolve(what);
    });
}

Unfortunately, this method is giving me a broken link in the element that it's going into. The image doesn't display, despite console.log printing out a similar base64 string as the working one.

Can anyone please help me figure out what's wrong with this thing?

CodePudding user response:

There are multiple issues with your resizeImage function.

  1. You resolve what before the image was loaded and resized. You return a Promise that will resolve to ''.
  2. You onload callback has a second image. The canvas will draw this empty image instead of the loaded one.
resizeImage(imageURL: any): Promise<any> {
    return new Promise((resolve) => {
      var image = new Image();
      image.onload = function () {
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        if (ctx != null) {
          ctx.drawImage(image, 0, 0, 640, 480);  // <-- draw the right image!
        }
        var data = canvas.toDataURL('image/png', 0.5);
        resolve(data);   // <-- call it here!
      };
      image.src = imageURL;
    });
}
  •  Tags:  
  • Related