You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity C#中如何通过REST API以图片文件形式发送抓拍图像?

问题描述

我目前用Unity捕获WebcamTexture图像并以字节数组形式发送给机器学习图像分类API,现在希望改为以图片文件形式发送。

捕获图像的代码:

public void SavePhoto()
{
    Debug.Log(Application.dataPath);
    Texture2D photo = new Texture2D(camTexture.width, camTexture.height);
    photo.SetPixels(camTexture.GetPixels());
    photo.Apply();

    //Encode to a PNG
    byte[] bytes = photo.EncodeToJPG();

    System.IO.File.WriteAllBytes(Application.dataPath + "/photo.png", bytes);
    predictImage(bytes);
}

发送API的代码:

public async void predictImage(byte[] bytes)
{
    ByteArrayContent content = new ByteArrayContent(bytes);
    
    var response = await client.PostAsync("http://74.235.83.70:80", content);
    var responseString = await response.Content.ReadAsStringAsync();
    Debug.Log(responseString);
}
解决方案

要以图片文件形式发送,本质是模拟HTTP表单上传文件(multipart/form-data),这是绝大多数机器学习图像分类API接收文件的标准方式。你需要修改predictImage方法,使用MultipartFormDataContent来包装文件内容:

修改后的代码

public async void predictImage(byte[] bytes)
{
    // 创建Multipart表单内容
    using (var multipartContent = new MultipartFormDataContent())
    {
        // 将字节数组包装为文件内容,指定MIME类型
        var fileContent = new ByteArrayContent(bytes);
        // 匹配图片编码格式:JPG用"image/jpeg",PNG用"image/png"
        fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
        
        // 添加到表单,参数名需和API要求一致(常见为"file"/"image")
        multipartContent.Add(fileContent, "file", "photo.jpg");

        // 发送请求
        var response = await client.PostAsync("http://74.235.83.70:80", multipartContent);
        var responseString = await response.Content.ReadAsStringAsync();
        Debug.Log(responseString);
    }
}

关键说明

  • MultipartFormDataContent是HTTP上传文件的标准载体,API能识别这是文件上传请求
  • 注意匹配ContentType和图片编码格式:如果用EncodeToPNG()就设为"image/png",用EncodeToJPG()则设为"image/jpeg"
  • multipartContent.Add的第二个参数(示例中为"file")是API期望的表单字段名,需和API文档要求一致
  • 第三个参数(示例中为"photo.jpg")是上传时的文件名,建议和实际图片格式对应,部分API会通过文件名判断类型

另外,你当前SavePhoto方法里的注释写着"Encode to a PNG",但实际调用的是EncodeToJPG(),建议统一两者,避免混淆。

内容的提问来源于stack exchange,提问作者Roshan Ojha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 06:40:46