Question

Converting Bitmap in 2D Array

Asked by: andy06

Hi everyone ,
I'm doing image processing for the first time and I'm working with VC++ 6.0 under WinXP.
I would like to create a function which loads an 8 bit grayscale bitmap image and convert it
into a 2D array where each element represents one of the image's
pixel intensities for further purposes e.g. to calculate the fft.I saw quite similar
examples on this homepage but none of them returns an 2D array.
My code is attached in Code Snippet
The problem is that I would like to have the values of the array returned and I don't know how it should look like inside LRESULT CALLBACK WndProc function(I'm using Win32 API).And I'm also getting error message because of following declarations:
BYTE  tempScanLine[WIDTH * 1]  // error C2057:it should be a constant expression
                                                    //error C2466 : can't reserved an array of size 0
                                                 //  error C2133: 'tempScanLine' : unknown parameter
const double grayscale[WIDTH*HEIGHT]; //  error C2133: 'grayscale' : unknown parameter
I thought of writing grayscale=new double [WIDTH*HEIGHT] but then I have to give the memory free
and I can't return the array anymore right?
Thank you

LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{	
static HBITMAP hbitmap;
int WIDTH, HEIGHT;
switch (message)
     {
   case WM_PAINT:
				
HANDLE hObj = LoadImage(NULL,"image.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
HDC hdc = CreateCompatibleDC(NULL);
SelectObject(hdc, hObj);
BITMAPINFO bInfo;
bInfo.bmiHeader.biSize = sizeof(bInfo.bmiHeader);
bInfo.bmiHeader.biWidth = WIDTH;
bInfo.bmiHeader.biHeight = HEIGHT;
bInfo.bmiHeader.biPlanes = 1;
bInfo.bmiHeader.biBitCount = 8; 
bInfo.bmiHeader.biCompression = BI_RGB;
BYTE tempScanLine[WIDTH ];
BYTE info[HEIGHT][WIDTH][1];
BITMAPINFO bi;
ZeroMemory(&bi, sizeof(BITMAPINFO));
bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
int count = HEIGHT - 1;
const double grayscale[WIDTH*HEIGHT];
for(int j = 0; j < HEIGHT; ++j)
{
      // find the width of the object
      GetDIBits(hdc, (HBITMAP) hObj, j, 1, NULL, &bi, DIB_RGB_COLORS);
 
      // store the color values in a 3D array of bytes
      GetDIBits(hdc, (HBITMAP) hObj, j, 1, tempScanLine, &bInfo, DIB_RGB_COLORS);
      for(int z = 0; z < bi.bmiHeader.biWidth; ++z)
      {
            info[count][z][0] = tempScanLine[(z * 1) + 2];    
            info[count][z][1] = tempScanLine[(z * 1) + 1];     
            info[count][z][2] = tempScanLine[(z * 1) + 0];                   
          //Transform to gray values
            grayscale[z]=info[count][z][0]*0.299 + info[count][z][1]*0.587+info[count][z][2]*0.114;
      }
     --count;
}
                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2008-03-05 at 00:39:43ID23215272
Tags

C++

,

image processing,bitmap,Win32 API

Topics

Microsoft Visual C++

,

Microsoft Visual C#.Net

,

Signal Processing

Participating Experts
2
Points
450
Comments
22

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. How to covert a Bitmap to an array of...
    How I can covert a Bitmap to an array of integer or to an array of string. And How I can convert this array to a Bitmap ? Thanks.
  2. bitmap reading - VC++
    Howto read bitmap and transform it into tiles collection?
  3. Scaling Bitmaps
    hi there ! I want to scale a bitmap (say 4000 x 4000 pixels) down to 200 x 200. If I use the Windows API functions the result isn't satisfactory. Can't recognize the details. Therefore I need a function which does something like anti aliasing. like paint shop pro resize fun...
  4. Create bitmap from array.
    I know that manipulating bitmap's pixels is quite slow, even with scanline. So I want to create 2 dimensional array of TColor and I want to create bitmap based from that array. So, each time I have to manipulate the pixels, I manipulate the array and then recreate any bitmap...
  5. Array to Bitmap
    This is probably something stupid I'm forgetting to do but Here is what I'm trying to achieve : I'm building a class, derived from CBitmap, called CBMP, for use in implementing some image processing algorithms. As such, it needs to be able to do the following : 1. Extract t...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: abosultanPosted on 2008-03-05 at 09:37:30ID: 21052467

I suggest you to use opencv library since you work on VC and first time on image processing; it can help you if you like to continue in this field
have a look at Open cv
http://www.site.uottawa.ca/%7Elaganier/tutorial/opencv%2Bdirectshow/cvision.htm

 

by: abosultanPosted on 2008-03-05 at 09:58:25ID: 21052688

I post a code tested in borland c++, so some few changes need te be altered.
there you see some dynamic array declaration , instead you have to modify by pointer(dynamic allocation) as a dynamic array;

typedef Graphics:: TBitmap TTBitmap; 
typedef DynamicArray<byte> TTByteArray;
typedef DynamicArray<TTByteArray> TImageArray;
/***********
 
TImageArray GetArrayOfImage(int BytePerPixel, TTBitmap  *pBitmap)
{
     Byte  *ptr;
     TImageArray Result;
    try
     {
      int h = pBitmap->Height;
      int w = (pBitmap->Width)*BytePerPixel;
      Result.set_length(h);
      for  ( int  y = 0; y < h; y++)
      {
        Result[y].set_length(w);
        ptr = (byte *)pBitmap->ScanLine[y];
         for  ( int  x = 0; x < w; x++)
                        Result[y][x] = ptr[x];
      }
    }
     catch  (...)
    {
      ShowMessage("Could not load or alter bitmap");
    }
    return Result;
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:

Select allOpen in new window

 

by: andy06Posted on 2008-03-05 at 22:42:30ID: 21057906

As I am working with Microsoft VC++ 6.0, what should be appropriate to replace TTBitmap  , TTByteArray with?Do I have to define a Class for Bitmap?If I have to use pointer in order to store the pixels I would have to use pointer auf pointer right? How is the function set_length() define?what about ScanLine?I can't see the definition for it anywhere. Where in the above code should be the file loaded and opened?
I downloaded the class Cximage on the following website:
http://www.codeproject.com/KB/graphics/cximage.aspx
Do you have an idea ow I could use that class in order to store the pixel in an 2D array?

 

by: abosultanPosted on 2008-03-06 at 05:42:06ID: 21060005

>> what should be appropriate to replace TTBitmap  
I'm not so expert in VC, but instead of Tbitmap, you can see HBITMAP, CBitmapclass in Vc++
> TTByteArray
TTByteArray is dynamic 1D array of bytes, you can use instead a dynamic allocation by pointers
for exemple
BYTE *buffBitmap = new BYTE[];

>>function set_length()
since I had used dynamic array, this function set a new size to the array in each step of adding an element in it;
>> ScanLine[];
is a function to indicate (set pointer) to a row, which in turn has his own pixels(columns)

 

by: DanRollinsPosted on 2008-03-08 at 14:35:24ID: 21078952

First of all, don't put something like that in your WM_PAINT handler.

Here is how I'd proceed in experimenting with and learning about these issues:

1) Create new dialog-based MFC application.
2) Add a smallish gray-scale image to your resources (IDB_BITMAP1)
3) Add a picture control to your dialog box, Set properties:
       ID: IDC_MyBmpCtrl           <<--- important: not IDC_STATIC
       Type: bitmap
       Image: IDB_BITMAP1
    The image is now automatically displayed for you!
4) Click on the bitmap in the dialog and press Ctrl+W (class wizard)
5) Click Member Variables; select IDC_MyBmpCtrl
6) Click [Add Variable]
     Member name: m_ctlMyBmp
    Category: Control
    Variable TYpe: CStatic
7) Add a button to the dialog (IDC_BUTTON1)
8) Double click it (add dlg member function OnButton1()
    Put this text there:
      MessageBox("You rang?");

After that, you now can start experimenting.  The image is automatically loaded and displayed.  When you click a button, some specific code will be executed.  You can obtain the HBITMAP my using:
     HBITMAP hBmp= m_ctlMyBmp.GetBitmap()
You can use the various CBitmap functions by:
    CBitmap* pcBmp= CBitmap::FromHandle( hBmp );
and then...
   CSize cs= pcBmp->GetBitMapDimension().
... and so forth.

When you get to this point, and have read up on CBitmap class object, let me know, and we'll take it to the next step.

-- Dan

 

by: andy06Posted on 2008-03-12 at 10:40:33ID: 21108651

Hi,
I've never used MFC before and it took some time to reach until step 4.At Step four  I was asked to create a new Class!(I named the Class MyBitmap).the MessageBox should be then in the function "void MyBitmap::OnButton1" right?Where should I write the following statements?
HBITMAP hBmp= m_ctlMyBmp.GetBitmap();
CBitmap* pcBmp= CBitmap::FromHandle( hBmp );
CSize cs= pcBmp->GetBitMapDimension()?
Thank you


 

by: DanRollinsPosted on 2008-03-12 at 23:52:23ID: 21113858

You should not have needed to create a new class object -- only a new member function for the CDialog-derived object that is the main (only) window your new program has.

Assuming that your project name is MyTestApp...
The OnButton1 function will be a member of CMyTestAppDlg (the ClassWizard will place it into the MyTestAppDlg.cpp source file.

 

by: andy06Posted on 2008-03-13 at 02:48:21ID: 21114492

I've seen where my mistake was.I was asked to create a new class
because I created a new dialog for the picture instead of using
the Dialog which was already generated by VC++.The function OnButton1()
is now at the right place.no error by compiling but the bitmap is not displayed at all.I'm having only
a blank page.....
What about
HBITMAP hBmp= m_ctlMyBmp.GetBitmap();
CBitmap* pcBmp= CBitmap::FromHandle( hBmp );
CSize cs= pcBmp->GetBitMapDimension()?
Should they be put in (I renamed my project MyTestApp) MyTestAppView.cpp?
thank you

 

by: DanRollinsPosted on 2008-03-13 at 19:51:23ID: 21122712

>> I'm having only
a blank page.....

This leads me to think that perhaps you did not create a Dialog-based application.  That option is on the first page presented by the AppWizard.  Revised detail for step #1:

1a) menu:  File / New...  
1b) Select Projects tab
1c) Select MFC AppWizard [exe]   / Project name: MyTestApp / [OK]
1d) Select Dialog based [Finished]

(Your empty dialog is displayed.)

 

by: andy06Posted on 2008-03-17 at 02:19:10ID: 21140652

You are right.I hadn't created a Dialog-based application but a SDI application.
Now my 8bpp grayscale image is automatically loaded and displayed.  By clicking on the button1 a message is also displayed.  
How could I now store the pixel intensities in an array where each element represents one of the image's pixel intensities?
Thank you

 

by: DanRollinsPosted on 2008-03-17 at 16:22:38ID: 21147293

OK, here's the next step.  Put this code into the OnButton1 handler:

      HBITMAP hBmp= (HBITMAP)LoadImage(NULL,"c:\\temp\\test.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);

      m_ctlMyBmp.SetBitmap( hBmp );

      CBitmap* pcBmp= CBitmap::FromHandle( hBmp );

      BITMAP rBmp;
      int n= pcBmp->GetBitmap( &rBmp );

But use a filename of a bitmap you want to work with.  I suggest you make a small one, say 10x10 or 32x32 for testing purposes.  First run the revised code:  You should see the desired bitmap appear in the control.

Next, put a breakpoint on the last line.   Single-step it.  Now use the debugger to examine the filled-in values in rBmp (a BITMAP structure).  It will provide the dimensions of the newly-loaded bitmap and other information.  Report what it says for
    rBmp.bmBitsPixel
and
    rBmp.bmPlanes

This is important for the next step, because some "grayscale" images are really full-color images.

 

by: andy06Posted on 2008-03-18 at 07:46:42ID: 21151575

I loaded for testing purposes a colored 32x32 bitmap and a grayscale 26x24 bitmap.For the 32x32 bitmap I become as information:
rBmp.bmWidth=32
rBmp.bmHeight=32
rBmp.bmBitsPixel=32
rBmp.bmPlanes=1
and  for the grayscale 26x24 bitmap I'm having:
rBmp.bmBitsPixel=32
rBmp.bmPlanes=1
I also tested all other "grayscale" bitmap(with dimensions 256x256) I had and it happened that they are all 32Bpp Bitmap with rBmp.bmPlanes=1.
that means I thought I was handling with 8Bpp grayscale image and in fact they weren't right?
thank you

 

by: andy06Posted on 2008-03-19 at 05:44:58ID: 21160861

As I'm not working with 8Bpp bitmap how does the next step look like?
thank you

 

by: DanRollinsPosted on 2008-03-19 at 14:00:35ID: 21165849

The simplest, and easiest-to-understand tool that is available to you is:

    GetPixel(x,y)

It returns a COLORREF value that represents the intensity of each of the Red, Green, Blue (RGB) components of the single pixel at the designated position.

In order to access that function, the bitmap must be selected into a "DC" (Device Context).  Because we have set up a test scenario in which the bitmap is already being displayed, this is easy.

Your next step is to experiment with this as follows:
1) Use the code (in the attachment, below) in your OnButton1 handler (or add an OnButton2 handler... whatever)

2) Click the button to see the result.
    An all-white pixel will be (255,255,255) and an all-black one will be (0,0,0).  
    In a color bitmap, an all-red pixel will be (255,0,0) and so forth,

3) Open Paintbrush or other bitmap editor and change the color of the pixel in the top left corner (x=0, y=0).  Save the bitmap and click the button in your dialog box.  You should see the new result -- both visibly in the displayed bitmap (that one pixel will change color) and in the message box.

4) You can now experiment with accessing other pixels.  

5) If you want, you can modify the bitmap.  Add another button and use CDC::SetPixel() For instance:

void CD39Dlg::OnButton4()
{
      CDC* pCDC= m_ctlMyBmp.GetWindowDC();

      pCDC->SetPixel(0,0, RGB(255,0,0) );
      pCDC->SetPixel(1,0, RGB(255,0,0) );
      pCDC->SetPixel(0,1, RGB(255,0,0) );
      pCDC->SetPixel(1,1, RGB(255,0,0) );
}

When you click that (newly-added button) the four pixels in the top/left corner will turn red.

If you have a grayscale bitmap, then your RGB values will be all the same... e.g.,
   (0,0,0)= black;
   (32,32,32)= very light gray,
   (127,127,127) is medium gray,
   (255,255,255)= pure black,
etc.

=-=-=-=-=-=-=-=-=-=
If you have a particular (smallish) gray-scale bitmap that you want to experiment with (and about which you have questions), you can attach it to your next comment, and I'll refer to it in subsequent comments of my own.

-- Dan

void CD39Dlg::OnButton3() 
{
	HBITMAP hBmp= (HBITMAP)LoadImage(NULL,"c:\\temp\\test.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
 
	m_ctlMyBmp.SetBitmap( hBmp );
 
	CDC* pCDC= m_ctlMyBmp.GetWindowDC();  // get access to DC-related fns
	
	COLORREF clrRGB= pCDC->GetPixel(0,0); // <<--- grab the dot in the top, left corner
	int nRed=   GetRValue( clrRGB );
	int nGreen= GetGValue( clrRGB );
	int nBlue=  GetBValue( clrRGB );
 
	CString s; s.Format( "Red=%d, Blue=%d, Green=%d", nRed, nBlue, nGreen );
	MessageBox( s );
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:

Select allOpen in new window

 

by: andy06Posted on 2008-03-31 at 05:32:53ID: 21244741

The step 1) until step 5) work all  fine. Thank you very much for the detailed explanations.
In the MSDN website the function GetPixel is defined like this:
COLORREF GetPixel(
  HDC hdc,   // handle to device context
  int nXPos,  // x-coordinate of pixel
  int nYPos  // y-coordinate of pixel
)
Why did you use only two arguments instead of three when calling GetPixel?
Was it possible in order to retrieve the red, green and blue value of a pixel to use the RGBQUAD structure?
Thank you

 

by: abosultanPosted on 2008-03-31 at 07:14:04ID: 21245520

>>Why did you use only two arguments instead of three when calling GetPixel?
I'm not sure If I could answer like DanRollins, but anyway I found another representation in MSDN
http://msdn2.microsoft.com/en-us/library/system.drawing.bitmap.getpixel(vs.71).aspx

it may be pertinent

 

by: DanRollinsPosted on 2008-03-31 at 12:35:19ID: 21248374

The ::GetPixel() API function
     http://msdn2.microsoft.com/en-us/library/ms532282.aspx
requires an HDC parameter.  But you will recall that I used the syntax:

    pCDC->GetPixel(0,0);

which uses the similar function that is a member of the CDC class object.  That object already knows the HDC, and it uses it when it calls the underlying API function.

>> Was it possible in order to retrieve the red, green and blue value of a pixel to use the RGBQUAD structure?

I'm not certain what you mean by this.  
The RGBQUAD and COLORREF structures are functionally similar ways to looks at a 32-bit value that contains the RGB information used to describe the color of a pixel.

 

by: andy06Posted on 2008-04-01 at 01:38:05ID: 21252177

Ok it appears clearly to me now.
I've attached two bitmaps that I'm working with.
How does the next step looks like?
Thank you

 

by: DanRollinsPosted on 2008-04-01 at 20:20:44ID: 21259968

OK, here's a little piece of code that reades each pixel in the image, and if it is not nearly white, it darkens it.

Again, this is mostely so that you can "get the feel" for reading pixels from an image into a 2-d array, doing something with them, then putting them back into the image.

void CD42Dlg::OnButton2() 
{
	HBITMAP hBmp= (HBITMAP)LoadImage(NULL,"c:\\temp\\cube.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
 
	m_ctlMyBmp.SetBitmap( hBmp );
 
	CBitmap* pcBmp= CBitmap::FromHandle( hBmp );
 
	BITMAP rBmp;
	int n= pcBmp->GetBitmap( &rBmp );
 
	int nWide= rBmp.bmWidth;
	int nHigh= rBmp.bmHeight;
 
 
	BYTE abPixels[300][300]; // for sample simplicity, just create 2-d array here.
 
	CDC* pCDC= m_ctlMyBmp.GetWindowDC();  // get access to DC-related fns
 
	int x,y;
	for ( x=0; x<nWide; x++ ) {
		for ( y=0; y<nHigh; y++ ) {
			COLORREF clrRGB= pCDC->GetPixel(x,y); 
			abPixels[x][y]= GetRValue( clrRGB );  // RGB all are the same, so take red
		}
	}
 
	// example: Darken all non-white pixels
 
	COLORREF clrRGB;
	for ( x=0; x<nWide; x++ ) {
		for ( y=0; y<nHigh; y++ ) {
			int nIntensity= abPixels[x][y];
			if (nIntensity < 220 ) { // if not "nearly white" ...
				nIntensity -= 20;    // make it somewhat darker
				if (nIntensity < 0 ) {
					nIntensity= 0;
				}
				clrRGB= RGB( nIntensity, nIntensity, nIntensity );
				pCDC->SetPixel( x,y, clrRGB ); // replace previous value with new, darker value
			}
		}
	}
 
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:

Select allOpen in new window

 

by: andy06Posted on 2008-04-02 at 07:45:29ID: 21263573

I have a question at line 24 of your code.What happens when RGB are not all the same?do I have to include a  if-clause?
Isit possible to use a function of my own on abPixels[x][y]= GetRValue( clrRGB )?(line 24)  
The code depends on the fact that a dialog-based application has been used.It is possible to read each pixel of the image without displaying it by using MFC of course?
thank you

 

by: andy06Posted on 2008-04-02 at 07:56:01ID: 31436808

clearly answers and thank you for having so much patience

 

by: DanRollinsPosted on 2008-04-02 at 12:19:22ID: 21266418

"...all the same" refers to the fact that it is a grayscale image.  
That means that when in memory, for use by a color device (the screen) the R,G, and B values will always be equal.  That provides 256 levels of whiteness.  Consider that if the values were not all the same --  say there was more red than green -- then the image would contain non-gray pixels.

As to the fact that there is a dialog box involved...
The only reason for that is to make it easy to see the results of experiments.  The functionaity would be the same if you never display the image.  For instance, the only relevant difference is that the above code uses:

    m_ctlMyBmp.SetBitmap( hBmp );

so that you can physically *see* the bitmap.  It is perfectly valid to make changes to the pixel data without ever displaying the image anywhere.  The fact that a dialog box is used is not part of that equation.  You could just as easily create an off-screen DC and manipulate the pixels there.

Thanks for the points and the grade :-)

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...