How to read picture in HDC

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include "stdafx.h"
#include "iostream"
#include "conio.h"
#include "windows.h"


using namespace std;

void main(){
	HDC hdc = GetDC(NULL);
	DWORD color = GetPixel(hdc, 500, 500);

	unsigned int r = GetRValue(color);
	unsigned int g = GetGValue(color);
	unsigned int b = GetBValue(color);

	cout << "red: " << r << endl;
	cout << "green: " << g << endl;
	cout << "blue: " << b << endl;

	system("pause");
}


From this code I think it reads pixel from screenshot
I want to read from file

I think I have to change this line
HDC hdc = GetDC(NULL);
but I don't know how to
please help me

Thank you
Last edited on
Since you use GDI(the older graphical API) I'll give a GDI answer.

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
#include "stdafx.h"
#include "iostream"
#include "conio.h"
#include "windows.h"


using namespace std;

void main(){
        LPCWSTR file = L"c:\image.bmp";
        HDC hdc = CreateCompatibleDC(NULL);
        HBITMAP bmp = (HBITMAP)LoadImageW(NULL, file, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
        HBITMAP hold = (HBITMAP)SelectObject(hdc, bmp);

	DWORD color = GetPixel(hdc, 500, 500);

	unsigned int r = GetRValue(color);
	unsigned int g = GetGValue(color);
	unsigned int b = GetBValue(color);

	cout << "red: " << r << endl;
	cout << "green: " << g << endl;
	cout << "blue: " << b << endl;

        SelectObject(hdc, hold);
        DeleteObject(bmp);
        DeleteDC(hdc);

	system("pause");
}


Use GetDIBBits() instead of GetPixel() if you plan to do alot of reading and writing of pixels. It'll be much faster.
Last edited on
Thank you ,you save my life
Where do you learn from?
Can I have another question?

I want to manually input file location from compiled program
from yours code

How can I do?

Thank you
Last edited on
You know how C++ IO works I assume? You can prompt for a filename that way. Or use command-line arguments, like so:

1
2
3
4
int main(int argc, char* argv[])
{
    //argv[1] should be first argument, argv[2] is second, etc
}


then run your program like so:

C:\>yourprog.exe image.bmp


You can open a file dialog to browse for files using the Common Item Dialog API, but that's more complicated:

http://msdn.microsoft.com/en-us/library/windows/desktop/bb776913%28v=vs.85%29.aspx
Last edited on
Thanks :)
Topic archived. No new replies allowed.