将C#中的位图转换为C++

Bitmap in C# into C++

本文关键字:转换 C++ 位图      更新时间:2023-10-16

对于在C++中使用位图的人来说,这一定是一个简单的问题。我有一个C#中的工作代码-如何在C++中做类似的事情??感谢您的代码(帮助):-)

public Bitmap Visualize ()
{

  PixelFormat fmt = System.Drawing.Imaging.PixelFormat.Format24bppRgb;
  Bitmap result = new Bitmap( Width, Height, fmt );
  BitmapData data = result.LockBits( new Rectangle( 0, 0, Width, Height ), ImageLockMode.ReadOnly, fmt );
  unsafe
  {
    byte* ptr;
    for ( int y = 0; y < Height; y++ )
    {
      ptr = (byte*)data.Scan0 + y * data.Stride;
      for ( int x = 0; x < Width; x++ )
      {
          float num = 0.44;
          byte c = (byte)(255.0f * num);
          ptr[0] = ptr[1] = ptr[2] = c;

          ptr += 3;
      }
    }
  }
  result.UnlockBits( data );
  return result;
}

到C++/CLI的原始翻译,我没有运行这个示例,所以它可能包含一些拼写错误。无论如何,在C++中有不同的方法可以获得相同的结果(因为您可以使用标准的CRTneneneba API)。

Bitmap^ Visualize ()
{
  PixelFormat fmt = System::Drawing::Imaging::PixelFormat::Format24bppRgb;
  Bitmap^ result = gcnew Bitmap( Width, Height, fmt );
  BitmapData^ data = result->LockBits( Rectangle( 0, 0, Width, Height ), ImageLockMode::ReadOnly, fmt );
  for ( int y = 0; y < Height; y++ )
  {
    unsigned char* ptr = reinterpret_cast<unsigned char*>((data->Scan0 + y * data->Stride).ToPointer());
    for ( int x = 0; x < Width; x++ )
    {
        float num = 0.44f;
        unsigned char c = static_cast<unsigned char>(255.0f * num);
        ptr[0] = ptr[1] = ptr[2] = c;
        ptr += 3;
    }
  }
  result->UnlockBits( data );
  return result;
}

您可以使用Easy BMP库进行非常相似的循环

C++在引用图像或处理图像时不包含任何内容。有许多库可用于此操作,并且对数据进行操作的方式可能各不相同。

在最基本的层次上,图像由一堆字节组成。如果您可以将数据(即,不是标头或其他元数据)提取到unsigned char[](或给定图像格式的其他适当类型)中,那么您可以像在C#示例中所做的那样迭代每个像素。