Rik
Rik

Reputation: 342

How to process image input to Angular app in an <img> element?

I am trying to create an Angular PWA that is able to take a picture, and after taking it to display it in an img element.

The first step I succeeded in: I now have an FAB button that opens the camera viewfinder (using the html input tag) with this small piece of code:

const element: HTMLElement = document.getElementById('imageCapturer') as HTMLElement;
element.click();

This simulates a click on the following HTML element:

<input type="file" accept="image/*" capture="environment" id="imageCapturer"">

However, after taking a picture I then want to use the image to render it in an img element (and also sending the image to a database with an API call)

I have tried multiple solutions including trying to add the file.name as src to the img element, and trying to create a new img HTML element with an attribute that uses the file. But I am still unable to process the image to be used in the img tag. Can somebody explain to me what the proper way to process the file is to be able to do this?

Cheers!

Upvotes: 1

Views: 3500

Answers (2)

Rik
Rik

Reputation: 342

I solved this problem in the following way:

First, I changed the HTML to this:

<input type="file" accept="image/*" id="imageCapturer" style="display: none;" (change)="useImage($event)">
<img *ngIf="URL" [src]="URL" id="imageViewer">

Then the function useImage looks like this:

useImage(event) {
if (event.target.files && event.target.files[0]) {
  const reader = new FileReader();

  reader.readAsDataURL(event.target.files[0]); // Read file as data url
  reader.onloadend = (e) => { // function call once readAsDataUrl is completed
    this.URL = e.target['result']; // Set image in element
    this._changeDetection.markForCheck(); // Is called because ChangeDetection is set to onPush
  };
}

}

Now whenever a new image is captured or selected it is updated in the view

Upvotes: 3

son pham
son pham

Reputation: 205

You can use event change of input file. This example:

$('#imageCapturer').on('change', function () {
   var input = $(this)[0];
   if (input.files && input.files[0]) {
        var fileName= input.files[0].name;
        var reader = new FileReader();
        reader.onload = function (e) {
            var buffer = e.target.result;
            var fileSize = input.files[0].size / 1024 / 1024; // in MB
            // SET IMG DISPLAY
            $('#image-display').attr('src', buffer).css({
                      'max-height': '170px',
                      'max-width': '170px',
        };
        reader.readAsDataURL(input.files[0]);
   }
});

Note: You add more attribute [enctype="multipart/form-data"] in tag form when sumbit form it will send file byte[].

<form id="process_form" method="POST" enctype="multipart/form-data" autocomplete="off" role="form" data-parsley-focus="none">

Upvotes: 1

Related Questions