使用For循环制作位图的最简单,最有效的方法

时间:2019-04-24 03:15:39

标签: c++ algorithm for-loop bitmap bitmapimage

我已经坚持了一段时间,最终我放弃了,但是任何人都可以引导我朝着正确的方向前进。另外请注意,我需要最终结果具有alpha。

static std::unique_ptr<unsigned char [ ]> ImageData;

    if ( !ImageData) {
        ImageData = std::make_unique<unsigned char [ ]>( Width* Height);

        for ( int x = 0; i < Width; x++) {
            for ( int y = 0; y < Height; y++ ) {
                float Red = 128, Green = 128, Blue = 255, Alpha = 255;
                // some cool math to determine color based off x/y.
                // . . .
                const unsigned char a[] = { Red, Green, Blue, Alpha };
                *reinterpret_cast<unsigned char*>(ImageData.get() + x + y * Height) = *a;
            };    
        };
    };

生成的图像完全是垃圾,无法使用,只是到处都是随机损坏。

1 个答案:

答案 0 :(得分:1)

  1. 您的问题不清楚,因为您未指定像素格式

    那么pixelformat 8/15/16/24/32 bpp是什么?哪个命令rgab / bgra?

  2. 为什么const char

    那不会随着位置而改变!!!并按照一些程序员的建议的建议,*a仅复制第一个BYTE,以便其余通道统一化,从而进行垃圾输出。

  3. 图像数据是char

    可以,但是指针算术是8位而不是32位!!!

  4. for(x...)循环内部有i,最有可能是thypo

  5. 为什么float个频道?

    这只会导致投放问题...

因此,如果我将所有内容放在一起,您的代码将无法按预期工作。为了解决这个问题,并假设其余代码(可视化)还可以,并且像素格式为32bpp,我将代码更改为:

typedef unsigned char BYTE;
typedef unsigned __int32 DWORD;
static std::unique_ptr<unsigned char [ ]> ImageData;
const int _r=0; // here change the RGB/BGR order
const int _g=1;
const int _b=2;
const int _a=3;
if ( !ImageData)
  {
  ImageData = std::make_unique<unsigned char [ ]>( Width* Height*4);
  int x,y,a;
  BYTE db[4];
  DWORD *dd=(DWORD*)(void*)db;
  DWORD *p=reinterpret_cast<DWORD*>(ImageData.get());
  for (a=0,y=0;y<Height;y++) 
   for (   x=0;x<Width;x++,a++)
     {
     // some cool math to determine color based on x,y.
     db[_r]=x;
     db[_g]=y;
     db[_b]=x+y;
     db[_a]=128;
     // copy pixel
     p[a]=*dd;
     }
  }

希望我没有将std::unique_ptr用作指针,所以将其强制转换为OK。我也直接在SO / SE编辑器中对其进行了编码,因此可能存在隐藏的较小语法错误或thypos。

相关问题