restful API接口接收图片 C#实现

需要一个web API接口用来接收图片,将客户上传的图片保存到服务器,如果直接用参数接收图片的base64编码的话,会得到参数超过最大长度的错误,那就换方式咯,改用frombody传递。
服务端代码:

[HttpPost]        
public string ImageUpload([FromBody]ImageUploadBody image_body)
{
    JsonViewData viewData = new JsonViewData() { isSuccessful = true, message = "" };
    try
    {
        string file_name = DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
        string save_path = System.Web.Configuration.WebConfigurationManager.AppSettings["UploadSavePath"];
        CBase64Helper.Base64StringToImage(image_body.image, System.IO.Path.Combine(save_path, file_name));
    }
    catch (Exception ex)
    {
        viewData.isSuccessful = false;
        viewData.message = ex.Message;
    }
    return JsonHelper.SerializeObject(viewData);
}

CBase64Helper.cs

    public class ImageUploadBody
    {
        public string name;
        public string image;
    }

    public static class CBase64Helper
    {
        public  static string ImgToBase64String(string Imagefilename)
        {
            try
            {
                Bitmap bmp = new Bitmap(Imagefilename);

                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                return Convert.ToBase64String(arr);
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public static void Base64StringToImage(string strbase64, string save_path)
        {
            try
            {
                byte[] arr = Convert.FromBase64String(strbase64);
                MemoryStream ms = new MemoryStream(arr);
                System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
                img.Save(save_path, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (Exception ex)
            {

            }
        }
    }

客户端代码,这里是用控制台程序上传的,页面JS代码因为不需要就没弄

    public class PostImageData
    {
        public string name;
        public string image;
    }

    public class JsonViewData
    {
        public bool isSuccessful
        {
            get;
            set;
        }
        public string message
        {
            get;
            set;
        }
    }
    public static class ImageUploadTool
    {
        public static bool UploadToServer(string img_file, ILog logger)
        {
            string url = "http://xxxxx/api/ImageUpload";

            string method = "POST";
            string base64 = CBase64Helper.ImgToBase64String(img_file);            
            PostImageData post_data = new PostImageData();
            post_data.image = base64;
            post_data.name = "";
            string bodys = Newtonsoft.Json.JsonConvert.SerializeObject(post_data);

            HttpWebRequest httpRequest = null;
            HttpWebResponse httpResponse = null;
            httpRequest = (HttpWebRequest)WebRequest.Create(url);
            httpRequest.Method = method;
            //根据API的要求,定义相对应的Content-Type
            httpRequest.ContentType = "application/json; charset=UTF-8";
            if (0 < bodys.Length)
            {
                byte[] data = Encoding.UTF8.GetBytes(bodys);
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }

            if (httpResponse.StatusCode != HttpStatusCode.OK)
            {
                logger.Error(img_file + " Upload failed, http error code: " + httpResponse.StatusCode);                
                Stream st = httpResponse.GetResponseStream();
                StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
                logger.Error(reader.ReadToEnd());
                return false;
            }
            else
            {

                Stream st = httpResponse.GetResponseStream();
                StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
                string str_res = reader.ReadToEnd();
                JsonViewData res = Newtonsoft.Json.JsonConvert.DeserializeObject<JsonViewData>(str_res);
                logger.Info(img_file + " Uploaded, success: " + res.isSuccessful.ToString());
                return res.isSuccessful;
            }            
        }
    }

客户端调用的时候直接:

CImageUploadTool.UploadToServer(img_path);
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Flask是一个基于Python的轻量级Web开发框架,可用于将yolo图像识别模型封装为Restful API。 首先,需要安装Flask框架和相关依赖项,包括numpy、opencv和yolo模型本身。接着,可以根据自己的需求编写一个Flask app,其包括以下主要功能: 1. 获得图像的URL或二进制数据 2. 调用预先加载的yolo模型 3. 处理yolo模型的输出结果 4. 将结果返回到客户端 为了优化API的性能,可以考虑以异步的方式调用yolo模型。可以使用Python的协程库(例如asyncio),或使用基于消息传递的工具(例如RabbitMQ),以异步方式处理多个模型调用请求。 最后,为方便客户端开发者使用API,可以提供文档和示例代码。可以使用Swagger或YAML等工具编写API文档,并提供基于不同编程语言的示例代码(例如Python、Java、JavaScript和C#等)。 综上所述,使用Flask将yolo图像识别模型封装为Restful API是一项相对容易实现的任务,但需要深入了解Flask框架、yolo模型和API设计。 ### 回答2: Flask是一个基于Python的web应用程序框架,适用于快速开发Python web应用程序。Yolo是一种对象检测的算法,可以在一张图像检测出对象的位置和所属类别。将Yolo图像识别模型封装为Restful API意味着可以通过网络API进行远程调用,将图像输入模型进行识别,并获得相应的识别结果。 在将Yolo模型封装为Restful API时,需要先写一个Flask应用程序。然后,将已经训练好的Yolo模型导入到应用程序。接下来,根据需要定义一个或多个RESTful API端点,并使其可以响应来自客户端的HTTP请求。在这些API端点,使用图像识别模型对输入图片进行识别,然后把输出结果返回给客户端。 具体来说,为了能够在Flask应用程序使用Yolo模型进行图像识别,需要将模型导入至Python的代码,并使用OpenCV或其他图像处理库对输入图片进行预处理。同时,要配置好Flask路由,定义API端点路径,并访问到模型去进行识别操作。 总结而言,将Yolo图像识别模型封装为Restful API的过程需要深入掌握Python语言和Flask框架的开发,同时也需要对图像识别领域有一定的了解。此外,在实现过程,需要保证模型能够高效地进行识别,并考虑到Python和Flask的性能问题。 ### 回答3: 在使用Flask将YOLO图像识别模型封装为RESTful API之前,需要进行以下步骤: 1.准备YOLO模型:首先,需要准备好YOLO模型。可以使用现有的预训练模型或根据自己的需要训练模型。 2.安装Flask和相关库:在使用Flask构建RESTful API之前,需要安装Flask和与之相关的库,例如flask-restful,flask-cors等。 3.编写Flask应用程序:编写Flask应用程序包括定义API端点,配置数据传输格式,处理请求和返回结果等。 具体步骤如下: 1.定义API端点:在Flask应用程序定义API端点是相当简单的,只需使用Flask的route装饰器和HTTP方法即可定义RESTful API。例如,可以使用POST方法将图像上传到服务器。 @app.route('/predict', methods=['POST']) def predict(): # 接收传输的图像 file = request.files['image'] image = Image.open(file.stream) # 调用模型进行预测 result = yolo_model.predict(image) # 返回预测结果 return jsonify(result) 2.配置数据传输格式:为了方便客户端和服务器端之间的数据传输,需要配置数据传输格式。使用json格式是比较常见的,可以使用Flask的jsonify函数轻松地将结果转换为json格式。 3.处理请求和返回结果:可以使用Flask的request对象获取传输的数据,使用jsonify函数返回结果。 通过以上步骤,可以将YOLO图像识别模型封装为RESTful API实现图像识别功能。客户端可以通过发送Post请求并传输图像数据,服务器端进行预测,并返回结果。这种方式可以很方便地实现模型的部署和使用,提高应用程序的可扩展性和可维护性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值