@@ -94,30 +94,41 @@ Napi::Value getImageBuffer(const Napi::CallbackInfo& info, bool useThumbnail) {
9494 if (GetObject (hBitmap, sizeof (BITMAP), &bmp) && bmp.bmWidth > 0 && bmp.bmHeight > 0 ) {
9595 std::wcerr << L" Bitmap: " << bmp.bmWidth << L" x" << bmp.bmHeight << std::endl;
9696
97+ int width = bmp.bmWidth ;
98+ int height = bmp.bmHeight ;
99+ int bmpSize = width * 4 * height;
100+
97101 BITMAPINFO bmi = {};
98102 bmi.bmiHeader .biSize = sizeof (BITMAPINFOHEADER);
99- bmi.bmiHeader .biWidth = bmp. bmWidth ;
100- bmi.bmiHeader .biHeight = -bmp. bmHeight ;
103+ bmi.bmiHeader .biWidth = width ;
104+ bmi.bmiHeader .biHeight = -height; // top-down
101105 bmi.bmiHeader .biPlanes = 1 ;
102106 bmi.bmiHeader .biBitCount = 32 ;
103107 bmi.bmiHeader .biCompression = BI_RGB;
104108
105- int bmpSize = bmp.bmWidth * 4 * bmp.bmHeight ;
106- std::unique_ptr<BYTE[]> pixels (new BYTE[bmpSize]);
107-
108- HDC hMemDC = CreateCompatibleDC (nullptr );
109- if (hMemDC) {
110- int lines = GetDIBits (hMemDC, hBitmap, 0 , bmp.bmHeight , pixels.get (), &bmi, DIB_RGB_COLORS);
111- if (lines > 0 ) {
112- std::wcerr << L" GetDIBits returned " << lines << L" scanlines." << std::endl;
113- result = Napi::Buffer<BYTE>::Copy (env, pixels.get (), bmpSize);
109+ BYTE* bits = nullptr ;
110+ HDC hdc = GetDC (nullptr );
111+ HBITMAP hDib = CreateDIBSection (hdc, &bmi, DIB_RGB_COLORS, reinterpret_cast <void **>(&bits), nullptr , 0 );
112+ HDC hMemDC = CreateCompatibleDC (hdc);
113+ ReleaseDC (nullptr , hdc);
114+
115+ if (hMemDC && hDib && bits) {
116+ HGDIOBJ old = SelectObject (hMemDC, hDib);
117+ HDC hSrcDC = CreateCompatibleDC (nullptr );
118+ if (hSrcDC) {
119+ SelectObject (hSrcDC, hBitmap);
120+ BitBlt (hMemDC, 0 , 0 , width, height, hSrcDC, 0 , 0 , SRCCOPY);
121+ DeleteDC (hSrcDC);
122+
123+ result = Napi::Buffer<BYTE>::Copy (env, bits, bmpSize);
114124 } else {
115- std::wcerr << L" GetDIBits failed or returned zero lines." << std::endl;
116- Napi::Error::New (env, " GetDIBits failed" ).ThrowAsJavaScriptException ();
125+ Napi::Error::New (env, " Failed to create source DC" ).ThrowAsJavaScriptException ();
117126 }
127+ SelectObject (hMemDC, old);
118128 DeleteDC (hMemDC);
129+ DeleteObject (hDib);
119130 } else {
120- Napi::Error::New (env, " CreateCompatibleDC failed " ).ThrowAsJavaScriptException ();
131+ Napi::Error::New (env, " Failed to create DIB section " ).ThrowAsJavaScriptException ();
121132 }
122133 } else {
123134 std::wcerr << L" Invalid bitmap dimensions." << std::endl;
0 commit comments