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

Easiest & Most Efficient Way to Making a Bitmap Using For Loops

本文关键字:最简单 有效 方法 位图 for 循环 使用      更新时间:2023-10-16

我已经坚持了一段时间,我最终放弃了,但谁能引导我走向正确的方向。另外请注意,我需要最终结果具有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. 您的问题不清楚,因为您没有指定像素格式

    那么BPP8/15/16/24/32像素格式是什么?哪个顺序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。