【问题标题】:How to process image input to Angular app in an <img> element?如何在 <img> 元素中处理 Angular 应用程序的图像输入?
【发布时间】:2018-10-31 21:17:17
【问题描述】:

我正在尝试创建一个能够拍照的 Angular PWA,并在拍照后将其显示在 img 元素中。

我成功的第一步:我现在有一个 FAB 按钮,可以用这段小代码打开相机取景器(使用 html 输入标签):

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

这模拟了对以下 HTML 元素的点击:

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

但是,在拍完照片后,我想使用图像在 img 元素中呈现它(并且还通过 API 调用将图像发送到数据库)

我尝试了多种解决方案,包括尝试将 file.name 作为 src 添加到 img 元素,并尝试使用使用该文件的属性创建一个新的 img HTML 元素。但是我仍然无法处理要在 img 标签中使用的图像。有人可以向我解释处理文件的正确方法是什么?

干杯!

【问题讨论】:

    标签: html angular typescript


    【解决方案1】:

    我通过以下方式解决了这个问题:

    首先,我将 HTML 更改为:

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

    那么函数useImage如下所示:

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

    }

    现在,每当捕获或选择新图像时,它都会在视图中更新

    【讨论】:

      【解决方案2】:

      您可以使用输入文件的事件更改。 这个例子:

      $('#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]);
         }
      });

      注意:您在标签形式中添加更多属性[enctype="multipart/form-data"],当sumbit形式它将发送文件字节[]。

      &lt;form id="process_form" method="POST" enctype="multipart/form-data" autocomplete="off" role="form" data-parsley-focus="none"&gt;

      【讨论】:

      • 感谢您的回答!这个解决方案对我不起作用,但它确实帮助我找到了适合我的问题的解决方案 :)
      猜你喜欢
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      • 2018-04-01
      • 2022-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      相关资源
      最近更新 更多