sourcecode

Angular 4/5+의 API에서 이미지를 얻는 중?

codebag 2023. 10. 25. 23:19
반응형

Angular 4/5+의 API에서 이미지를 얻는 중?

Angular 4를 이용한 개발은 처음입니다.API로부터 이미지 표시에 대한 응답을 받는 중에 문제가 발생했습니다.API에서 이미지 파일에는 입력 스트림 파일이 있습니다.검색해서 제대로 표시하는 방법을 모르겠습니다.

누가 해결해 줄 수 있습니까?

나는 이것을.

  • Image.Component.ts:

     this.http.get('http://localhost:8080/xxx/download/file/596fba76ed18aa54e4f80769')
              .subscribe((response) => { var blob = new Blob([response.text()], {type: "image/png"});
                console.log(blob);
                console.log(window.btoa(blob.toString()));           
     });
    

결과는 이 =>W29iamVjdCBCbG9iXQ==, 하지만 그것은 정확한 형식이 아닙니다.

그리고 이것도 시도해 봤습니다.

this.http.get('http://localhost:8080/xxx/download/file/596fba76ed18aa54e4f80769').map(Image=>Image.text())
  .subscribe(data => {
    console.log((data.toString()));   
});

결과는 =>

 ����\ExifII*��7                                                      ��DuckyK��fhttp://ns.adobe.com/xap/1.0/<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?> <x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.3-c011 66.145661, 2012/02/06-14:56:27        "> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <rdf:Description rdf:about="" xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/" xmlns:stRef="http://ns.adobe.com/xap/1.0/sType/ResourceRef#" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmpMM:OriginalDocumentID="xmp.did:0280117407206811A2188F30B3BD015B" xmpMM:DocumentID="xmp.did:E2C71E85399511E7A5719C5BBD3DDB73" xmpMM:InstanceID="xmp.iid:E2C71E84399511E7A5719C5BBD3DDB73" xmp:CreatorTool="Adobe Photoshop CC 2014 (Windows)"> <xmpMM:DerivedFrom stRef:instanceID="xmp.iid:7092a9cd-b3fd-bb49-b53c-9b6e1aa1ac93" stRef:documentID="adobe:docid:photoshop:40615934-3680-11e7-911d-f07c687d49b8"/> <dc:rights> <rdf:Alt> <rdf:li xml:lang="x-default">                                                      </rdf:li> </rdf:Alt> </dc:rights> <dc:creator> <rdf:Seq/> </dc:creator> </rdf:Description> </rdf:RDF> </x:xmpmeta> <?xpacket end="r"?>���Photoshop 3.08BIMJZ%Gt6                                                      8BIM%�<".}��νz��܌��Adobed����  

window.btoa를 사용하여 인코딩을 했었습니다. 라틴 범위가 아닌 오류여야 합니다.

설정해야 합니다.responseType: ResponseContentType.BlobGET-Request 설정에서 이미지를 blob으로 가져와 나중에 dabase64 인코딩된 소스로 변환할 수 있기 때문입니다.위의 코드는 좋지 않습니다.이 작업을 올바르게 수행하려면 API에서 이미지를 가져올 수 있는 별도의 서비스를 만듭니다.구성 요소에서 HTTP-Request를 호출하는 것은 좋지 않기 때문입니다.

작동 예는 다음과 같습니다.

만들다image.service.ts다음 코드를 입력합니다.

각도 4:

getImage(imageUrl: string): Observable<File> {
    return this.http
        .get(imageUrl, { responseType: ResponseContentType.Blob })
        .map((res: Response) => res.blob());
}

각도 5+:

getImage(imageUrl: string): Observable<Blob> {
  return this.httpClient.get(imageUrl, { responseType: 'blob' });
}

중요:Angular 5+ 이므로 새 제품을 사용해야 합니다.HttpClient.

더뉴HttpClient기본적으로 JSON을 반환합니다.다른 응답 유형이 필요한 경우 다음을 설정하여 지정할 수 있습니다.responseType: 'blob'. 그것에 대해서는 여기서 더 읽어보세요.

이제 당신은 당신의 컴퓨터에 몇 가지 기능을 만들어야 합니다.image.component.ts이미지를 가져와서 html로 보여주는 것.

Blob에서 이미지를 만들려면 자바스크립트의FileReader. 여기 새로운 기능이 있습니다.FileReader파일 리더의 load-Event를 들어봅니다.결과적으로 이 함수는 img src 속성에서 사용할 수 있는 base64 인코딩 이미지를 반환합니다.

imageToShow: any;

createImageFromBlob(image: Blob) {
   let reader = new FileReader();
   reader.addEventListener("load", () => {
      this.imageToShow = reader.result;
   }, false);

   if (image) {
      reader.readAsDataURL(image);
   }
}

이제 생성된 를 사용해야 합니다.ImageServiceapi에서 이미지를 가져올 수 있습니다.데이터를 구독하고 이 데이터를 다음에 제공해야 합니다.createImageFromBlob-기능.다음은 기능 예시입니다.

getImageFromService() {
      this.isImageLoading = true;
      this.imageService.getImage(yourImageUrl).subscribe(data => {
        this.createImageFromBlob(data);
        this.isImageLoading = false;
      }, error => {
        this.isImageLoading = false;
        console.log(error);
      });
}

이제 당신은 당신의imageToShow-HTML 템플릿의 변수는 다음과 같습니다.

<img [src]="imageToShow"
     alt="Place image title"
     *ngIf="!isImageLoading; else noImageFound">
<ng-template #noImageFound>
     <img src="fallbackImage.png" alt="Fallbackimage">
</ng-template>

이 설명이 이해하기 쉽고 프로젝트에 사용할 수 있기를 바랍니다.

여기서 Angular 5+의 작동 예를 참조하십시오.

각도 5 :

 getImage(id: string): Observable<Blob> {
    return this.httpClient.get('http://myip/image/'+id, {responseType: "blob"});
}

angular http를 사용할 필요가 없습니다. js native functions로 얻을 수 있습니다.

// you will ned this function to fetch the image blob.
async function getImage(url, fileName) {
     // on the first then you will return blob from response
    return await fetch(url).then(r => r.blob())
    .then((blob) => { // on the second, you just create a file from that blob, getting the type and name that intend to inform
         
        return new File([blob], fileName+'.'+   blob.type.split('/')[1]) ;
    });
}

// example url
var url = 'https://img.freepik.com/vetores-gratis/icone-realista-quebrado-vidro-fosco_1284-12125.jpg';

// calling the function
getImage(url, 'your-name-image').then(function(file) {

    // with file reader you will transform the file in a data url file;
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onloadend = () => {
    
    // just putting the data url to img element
        document.querySelector('#image').src = reader.result ;
    }
})
<img src="" id="image"/>

언급URL : https://stackoverflow.com/questions/45530752/getting-image-from-api-in-angular-4-5

반응형