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

在C#中将ushort[]数组转换为Jetmap彩色位图的问题

从ushort数组生成Jetmap彩色位图的修正方案

原代码存在的核心问题

  • 循环行列逻辑颠倒:原代码中y循环条件为y < xL、x循环条件为x < yL,混淆了图像的宽度(xL)和高度(yL),导致图像行列错位。
  • 颜色映射范围错误:数组取值是0-700,但调用JetColor时传入的vmax是255,导致大于255的数值全部被归一化为1,无法区分完整取值范围的颜色差异。
  • 像素格式不匹配:使用Format48bppRgb(16位每通道),但Color.FromArgb生成的是8位每通道颜色,SetPixel赋值时会出现精度丢失或显示异常。
  • 变量未声明:循环中的x、y变量缺少int修饰符,编译会报错。

修正后的完整代码

public Bitmap GetColorBitmap(ushort[] arr, int width, int height)
{
    // 使用24位RGB格式,匹配Color的8位通道标准
    var bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
    int count = 0;
    
    // 按高度(y轴)遍历行
    for (int y = 0; y < height; y++)
    {
        // 按宽度(x轴)遍历列
        for (int x = 0; x < width; x++)
        {
            // 传入数组实际取值范围0-700
            Color color = JetColor(arr[count], 0, 700);
            bitmap.SetPixel(x, y, color);
            count++;
        }
    }
    return bitmap;
}

public static Color JetColor(float v, float vmin, float vmax)
{
    // 避免除以0的异常情况
    if (vmax <= vmin)
        return Color.Black;
        
    float r = 0, g = 0, b = 0;
    float x = (v - vmin) / (vmax - vmin);
    
    // 标准Jet色阶逻辑:蓝→青→黄→红渐变
    if (x < 0.25f)
    {
        r = 0;
        g = 4 * x;
        b = 1;
    }
    else if (x < 0.5f)
    {
        r = 0;
        g = 1;
        b = 1 - 4 * (x - 0.25f);
    }
    else if (x < 0.75f)
    {
        r = 4 * (x - 0.5f);
        g = 1;
        b = 0;
    }
    else
    {
        r = 1;
        g = 1 - 4 * (x - 0.75f);
        b = 0;
    }
    
    // 转换为0-255的整数通道值
    return Color.FromArgb((int)(r * 255), (int)(g * 255), (int)(b * 255));
}

private static float Constrain(float value, float min, float max)
{
    return Math.Max(min, Math.Min(max, value));
}

额外说明

  • 修正后的JetColor函数采用标准Jet色阶算法,颜色渐变更符合行业通用的Jetmap效果。
  • 函数名改为帕斯卡命名法(GetColorBitmap),符合C#编码规范。
  • 添加了边界值判断,避免极端情况下的运行时异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 03:05:16