Programming C++Builder An example on using scanline to access bitmap pixels in C-Builder
Notice: Undefined variable: relatedArticlesCount in /home/wwwroot/codeback.net/plugins/content/tags.php on line 149

This is an example on how to use scanline to quick access and manipulate the pixels of a bitmap in C++Builder.

Ok, create a project, drag an image and a button onto the from. Then in the form's crate handler, adding a line of code to load an exists picture.

void __fastcall TForm1::FormCreate(TObject *Sender)
{
    Image1->Picture->Bitmap->LoadFromFile("C:\\mypicture\\mypic.bmp");
}
 

//Then in button1 click handler, assign following codes to use scanline to handle the bitmap.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    int *MemByte;
    int nWidth = Image1->Picture->Bitmap->Width;
    int nHeight = Image1->Picture->Bitmap->Height;
    MemByte = new int[(nWidth)*(nHeight)];

    for(int y = 0; y < nHeight; y++)
    {
        Byte *ptr = (Byte *)Image1->Picture->Bitmap->ScanLine[y];
        for(int x = 0;x < nWidth;x++)
        {
            int nGray = ptr[x*3]*0.114 + ptr[x*3+1]*0.587 + ptr[x*3+2]*0.299;
            if(nGray < 127)
                nGray = 192;
            else
                nGray = 255;
            ptr[x*3] = ptr[x*3+1] = ptr[x*3+2] = nGray;
            MemByte[nWidth*y+x] = nGray;
        }
    }

    int nSX,nSY;
    bool found = false;
    for(int x = 0; (x < nWidth) && (!found); x++)
    {
        for(int y = 0; y < nHeight; y++)
        {
            if(MemByte[nWidth*y+x] < 255)
            {
                Image1->Picture->Bitmap->Canvas->Pixels[x][y] = (TColor)RGB(0,0,0);
                found = true;
                nSX = x;
                nSY = y;
                break;
            }
        }
    }

    int nCX,nCY;
    bool End = false;

    int Dir[8][2] = {{0,-1}, {1,-1}, {1,0}, {1,1}, {0,1}, {-1,1}, {-1,0}, {-1,-1}};

    int Dirx = 0;
    nCX = nSX;
    nCY = nSY;
    while(!End)
    {
        int nNX,nNY;
        int alldir = 0;

        found = false;
        while(!found)
        {
            nNX = nCX+Dir[Dirx][0];
            nNY = nCY+Dir[Dirx][1];
            alldir ++;

            if(MemByte[nNY*nWidth+nNX] < 255)
            {
                found = true;
                nCX = nNX;
                nCY = nNY;
                if((nCX == nSX) && (nCY == nSY))
                End = true;
 
                Image1->Picture->Bitmap->Canvas->Pixels[nCX][nCY] = (TColor)RGB(255,0,0);

                Dirx --;
                if(Dirx < 0)
                    Dirx = 7;

                Dirx --;
                if(Dirx < 0)
                    Dirx = 7;
            }
            else
            {
                Dirx ++;
                if(Dirx == 8)
                    Dirx = 0;
            }
        }
    }
    delete MemByte;
}


Add comment


Security code
Refresh

Programming - C++Builder