0

I have marshalled PIL image into bytes via toBytes() on my Flask Server.

Then these bytes was then embedded in Json as a string and transferred via http to my Angular web application.

Is there a way to turn this binary into a viewable image on my web application? Or is there a better way transfering image from my Flask server to my Angular web application?

Ryan
  • 356
  • 1
  • 6
  • 26

1 Answers1

0

A part of my code python flask code:

    imgByteArrTemp = io.BytesIO()
    img.save(imgByteArrTemp, format="PNG")
#        imgByteArrTemp = base64.b64encode(imgByteArrTemp.getvalue())
    imgByteArrTemp = imgByteArrTemp.getvalue()

My GET method:

@app.route("/get-resulting-image", methods=["GET"]) 
def get_resulting_image(): 
    global q 
    if not q.empty(): 
        item = q.get() 
        return send_file(io.BytesIO(item),
                mimetype = "image/png",
                as_attachment=True,
                download_name="%s.png")
    return "no image to provide"

My typescript app.component.ts:

createImageFromBlob(image:Blob){
    let reader = new FileReader();
    reader.addEventListener("load", () => {
        this.imageBinary = reader.result;
        console.log(this.imageBinary);
    },false);
    if (image){
        reader.readAsDataURL(image);
    }
}   
getResponse(){
 ...
this.restService.getCorrespondingImage().subscribe( 
                            data1 => {
                                this.createImageFromBlob(data1);
                                this.isImageLoading = false;
                            },
                            error => {
                                this.isImageLoading = false;
                                console.log(error)
                            }
                        );
 ...
}

app.component.html

<img [src]="imageBinary" *ngIf="!isImageLoading">

rest.service.ts

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
import {catchError, retry} from 'rxjs/operators';
@Injectable({
    providedIn: 'root'
})
export class RestService {

    constructor(private http: HttpClient) { } 

....
    getCorrespondingImage():Observable<Blob>{
        return this.http.get(
            "http://192.168.1.2:9500/get-resulting-image",
            {responseType:"blob"});
    }   
}

Hope this could help someone out there.

Ryan
  • 356
  • 1
  • 6
  • 26