-1

I've been stuck on this for awhile, I eventually gave up but can anyone lead me in the correct direction. Also side note, I need the final result to have 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;
            };    
        };
    };

The image generated is completely trash and unusable, it's just random corruption everywhere.

Valena
  • 11
  • 4
  • 1
    The expression `*a` is equal to `a[0]`. That is, you only assign the `Red` value to each byte in the bitmap. – Some programmer dude Apr 24 '19 at 03:34
  • You want an array of [`RGBQUAD`](https://learn.microsoft.com/en-us/windows/desktop/api/wingdi/ns-wingdi-tagrgbquad) (if you don't have Windows headers, make your own structure) – Ben Voigt Apr 24 '19 at 04:16

1 Answers1

1
  1. You question is unclear as you did not specify pixel format

    so what is the pixelformat 8/15/16/24/32 bpp ? which order rgab / bgra ?

  2. why const char ?

    that would not change with position !!! and also as Some programmer dude suggested *a will copy just the first BYTE so the rest of the channels are unitialized hence garbage output.

  3. image data is char?

    that is OK but then the pointer arithmetics is 8 bit not 32 bit !!!

  4. for(x...) loop has i inside that is most likely a thypo

  5. why float channels?

    that only leads to casting problems ...

So if I put all together your code is not working at all as expected. To remedy it and assuming the rest of code (visualization) is OK and the pixel format is 32bpp I would change your code to this:

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;
     }
  }

Hope I did the pointer cast OK as I do not use the std::unique_ptr. Also I coded it directly in SO/SE editor so there might be hidden minor syntax errors or thypos.

Spektre
  • 49,595
  • 11
  • 110
  • 380