如何从 flask restful API return 图像?

How to return image from flask restful API?

我想 return 图像处理后。到目前为止,我能够将图像发送到服务器并进行处理。我如何 return 图像以便任何客户端都可以使用它?

class ImageProcessing(Resource):
 
    def __init__(self):
        parser = reqparse.RequestParser()
        parser.add_argument("image", type=werkzeug.datastructures.FileStorage, required=True, location='files')
        self.req_parser = parser
        
    def post(self):
        image_file = self.req_parser.parse_args(strict=True).get("image", None)
        if image_file:
            image = image_file.read()
            nparr = np.fromstring(image, np.uint8)
            img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
            img = process_img(img) 
            shape=img.shape
            return "Image recieved: Image size {}X{}X{}".format(shape[0],shape[1],shape[2])
        else:
            return "Image sending failed"

Curl url:

curl -X POST -F 'image=@data/test.jpg' http://127.0.0.1:5000/processImage

如何return处理后的图片?

没关系,我先将图像转换为 base64,然后将其作为字符串返回,从而解决了这个问题。

 rawBytes = io.BytesIO()
 img.save(rawBytes, "JPEG")
 rawBytes.seek(0)
 img_base64 = base64.b64encode(rawBytes.read())
 response = {
         "shape": shape,
         "image": img_base64.decode(),
         "message":"Image is BASE 64 encoded"        
      }
 return response,200