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

int[]转byte[]后数值缺失,图像保存失败求助(附C#代码)

问题分析与修复

你的代码核心问题有两个,导致生成的byte数组没有有效数据:

  1. 未接收AddByteToArray的返回值
    循环中调用AddByteToArray(bytePic, Convert.ToByte(arrPic[i]))时,该方法会返回新创建的数组,但你没有将返回值赋值回bytePic。因此最初初始化的空byte数组(全0)从未被修改,最终保存的自然是无效数据。

  2. AddByteToArray逻辑不符合需求
    这个方法的逻辑是创建一个比原数组长1的新数组,将原数组从索引1开始复制,新byte放在索引0。这既不是按顺序填充byte数组的逻辑,还会导致数组长度不断扩容,和你初始设定的arrPic.Length长度完全不符。


修复后的代码

直接去掉多余的AddByteToArray方法,在循环里直接给bytePic的对应索引赋值即可,这是把int数组转成byte数组的正确方式:

public string ChangeMaterialPicture(int[] arrPic, int materialId, string defaultPath)
{
    var material = _warehouseRepository.GetMaterialById(materialId);
    if (material is not null)
    {
        // Convert the Array to Bytes
        byte[] bytePic = new byte[arrPic.Length];
        for (var i = 0; i < arrPic.Length; i++)
        {
            // 直接将int转成byte后赋值到对应索引位置
            bytePic[i] = Convert.ToByte(arrPic[i]);
        }

        // Convert the Bytes to IMG
        string filename = Guid.NewGuid().ToString() + "_.png";
        string savePath = Path.Combine(defaultPath, "materials", material.VendorId.ToString(), filename);
        // 先检查并创建目录,避免保存失败
        Directory.CreateDirectory(Path.GetDirectoryName(savePath));
        System.IO.File.WriteAllBytes(savePath, bytePic);

        // Update the Image
        material.Picture = filename;
        _warehouseRepository.UpdateMaterial(material);

        return material.Picture;
    }
    else
    {
        return String.Empty;
    }
}

// 不再需要AddByteToArray方法

额外提示

  • 用Path.Combine拼接路径比字符串插值更安全,能自动适配不同系统的路径分隔符。
  • 保存文件前先创建目标目录,否则目录不存在时会抛出异常。
  • 确认arrPic中的int值范围在0-255之间,Convert.ToByte会对超出范围的值抛出异常;如果是图像像素值(比如单通道ARGB值),通常符合该范围,若为其他场景需额外处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 18:55:27