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

问题描述 投票:-1回答:1

我已经坚持了一段时间,我最终放弃了但是任何人都可以引导我走向正确的方向。另外注意,我需要最终结果才能获得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;
            };    
        };
    };

生成的图像完全是垃圾和无法使用,它只是随处可见的腐败。

c++ algorithm for-loop bitmap bitmapimage
1个回答
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。我也直接在SO / SE编辑器中对其进行编码,因此可能存在隐藏的次要语法错误或thypos。

© www.soinside.com 2019 - 2024. All rights reserved.