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

如何获取图像像素数?rectImage的pixelsCounter计数后仍为0的问题

问题分析与解决

你的循环逻辑存在两个关键错误,导致pixelsCounter始终为0:

  1. 起始坐标错误:rectImage是裁剪后的新位图,它的像素坐标从(0,0)开始,而非原裁剪区域的rect.X和rect.Y。如果rect.X或rect.Y大于等于rect.Width或rect.Height,循环根本不会执行。
  2. 终止条件错误:循环的终止值应该用rectImage.Width和rectImage.Height,而非原裁剪区域rect的宽高——rectImage的尺寸才是裁剪后实际的像素范围。

修正后的遍历计数代码

private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
{
    Bitmap rectImage = cropAtRect((Bitmap)pictureBox2.Image, rect);

    int x, y;
    pixelsCounter = 0; // 重置计数器,避免累加旧值

    // 遍历rectImage的所有像素
    for (x = 0; x < rectImage.Width; x++)       
    {
        for (y = 0; y < rectImage.Height; y++)           
        {
            Color pixelColor = rectImage.GetPixel(x, y);
            pixelsCounter++;
        }
    }

    pictureBox1.Image = rectImage;
}

更高效的方案

完全不需要遍历每个像素计数,直接用位图宽高相乘即可得到总像素数,性能远高于循环遍历:

private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
{
    Bitmap rectImage = cropAtRect((Bitmap)pictureBox2.Image, rect);
    pixelsCounter = rectImage.Width * rectImage.Height; // 直接计算总像素数
    pictureBox1.Image = rectImage;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:20:27