SoFunction
Updated on 2025-03-05

C++ Set transparent background picture

background:

There are two pictures, one is the target background picture, and the other is a color picture with its own background color

First draw this color picture into the target background picture, and this step can be achieved through BITBLT. But the effect after implementation is: on the target picture, the color picture drawn on it has its own background.

The problem is here. We want to remove the background of the color picture itself. How should we solve it?

Solution:

Use API function: TransparentBlt   This function draws the pictures in the original DC into the target DC and sets the transparent color of the original figure on the target graph.

BOOL TransparentBlt( 
 HDC hdcDest,    // handle to destination DC 
 int nXOriginDest,  // x-coord of destination upper-left corner 
 int nYOriginDest,  // y-coord of destination upper-left corner 
 int nWidthDest,   // width of destination rectangle 
 int hHeightDest,  // height of destination rectangle 
 HDC hdcSrc,     // handle to source DC 
 int nXOriginSrc,  // x-coord of source upper-left corner 
 int nYOriginSrc,  // y-coord of source upper-left corner 
 int nWidthSrc,   // width of source rectangle 
 int nHeightSrc,   // height of source rectangle 
 UINT crTransparent // color to make transparent 
);

For example, when the transparent color is set to the background color of the color graphic, after using this function, the background color of the color graphic on the resulting final graphic is eliminated.

CDC* pDC=GetDC(); 
 
CBitmap bmp; 
(IDB_BITMAP1); 
 
BITMAP bmpInfo; 
(sizeof(BITMAP),&bmpInfo); 
 
 
CDC ImageDC; 
(pDC); 
 
CBitmap *pOldImageBmp=(&bmp); 
 
 
CBitmap bmpBK; 
(IDB_BITMAP2); 
 
BITMAP bmpBkInfo; 
  (sizeof(BITMAP),&bmpBkInfo); 
 
CDC bkDC; 
(pDC); 
 
(&bmpBK); 
 
TransparentBlt(bkDC.m_hDC,100,150,,,ImageDC.m_hDC,0,0,,,RGB(255,0,0)); // Set red to transparent 
BitBlt(pDC->m_hDC,0,0,,,bkDC.m_hDC,0,0,SRCCOPY); //Draw on the screen

Principle: Implemented by setting the mask bitmap

1) First create the mask bitmap
2) Use the mask bitmap to act on the original color image to obtain a new mutation image (transparent color is black, other areas are primary colors)
3) Use the mask bitmap to match the target background image (the transparent area is transparent, and the other areas are black)
4) Use the new mutation image and the target background image or to obtain the final image

The above is the entire content of this article, I hope you like it.