MCPcopy Create free account
hub / github.com/ColorCop/ColorCop / AveragePixelArea

Method AveragePixelArea

ColorCop/ColorCopDlg.cpp:2718–2774  ·  view source on GitHub ↗

Compute the average RGB value of a square region centered on `point`.

Source from the content-addressed store, hash-verified

2716
2717// Compute the average RGB value of a square region centered on `point`.
2718bool CColorCopDlg::AveragePixelArea(HDC hdc, int* m_R, int* m_G, int* m_B, CPoint point) {
2719 // Compute the average RGB value of a square region centered on `point`.
2720 // The region size is (2 * m_iSamplingOffset + 1) on each side.
2721 int64_t reddec = 0, greendec = 0, bluedec = 0; // 64-bit to safely accumulate many pixel values
2722 int offset = m_iSamplingOffset;
2723 int elements = 0; // count only valid pixels
2724
2725 COLORREF crefxy;
2726 int xrel, yrel;
2727
2728 // Compute unclamped bounds
2729 int xmin = point.x - offset;
2730 int ymin = point.y - offset;
2731
2732 // Clamp lower bounds manually (avoids std::max(int, uint16_t) ambiguity)
2733 if (xmin < 0)
2734 xmin = 0;
2735 if (ymin < 0)
2736 ymin = 0;
2737
2738 // Walk the sampling region and accumulate RGB components.
2739 for (xrel = xmin; xrel <= point.x + offset; xrel++) {
2740 for (yrel = ymin; yrel <= point.y + offset; yrel++) {
2741 crefxy = ::GetPixel(hdc, xrel, yrel);
2742
2743 // Skip invalid pixels; GetPixel can fail near screen edges or on invalid DCs.
2744 if (crefxy == CLR_INVALID)
2745 continue;
2746
2747 reddec += GetRValue(crefxy);
2748 greendec += GetGValue(crefxy);
2749 bluedec += GetBValue(crefxy);
2750 ++elements; // count only valid samples
2751 }
2752 }
2753
2754 if (elements == 0) {
2755 // No valid pixels sampled; treat as unchanged.
2756 return true;
2757 }
2758
2759 // Convert accumulated totals into average RGB values.
2760 reddec /= elements;
2761 greendec /= elements;
2762 bluedec /= elements;
2763
2764 // Check whether the averaged color differs from the previously stored sample.
2765 // This avoids unnecessary updates when the sampled color hasn't changed.
2766 if (reddec != m_Reddec || greendec != m_Greendec || bluedec != m_Bluedec) {
2767 *m_R = static_cast<int>(reddec);
2768 *m_G = static_cast<int>(greendec);
2769 *m_B = static_cast<int>(bluedec);
2770 return false; // color changed
2771 }
2772
2773 return true; // color unchanged
2774}
2775

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected