调整HBITMAP的大小,同时保持透明背景

Resizing HBITMAP while keeping transparent background

本文关键字:透明 背景 HBITMAP 调整      更新时间:2023-10-16

我有一个应用程序,该应用程序加载具有透明背景的图像,然后我使用 StretchBlt将其调整到所需的大小,使用HALFTONE使用SetStretchBltMode(我尝试使用其他模式,然后使用其他模式来调整它保持透明度完好无损,也使调整大小的图像看起来"丑陋")。
但是,StretchBlt用颜色(黑色)代替透明背景,该背景不符合图像将要显示的窗口的背景。

所以我有两个选择:
1)用窗口的背景颜色替换图像的透明背景,然后使用StretchBlt
调整大小2)在保持背景透明度(首选选项)时调整大小

我尝试寻找可以提供任何功能的Winapi功能,但我没有发现。

我该如何使用普通的Winapi执行任何这些选项(在保持透明度或保持透明度的情况下进行调整大小)?

首先, BitBltStretchBltTransparentBlt不支持alpha频道。

TransparentBlt通过制作所需的任何特定颜色,透明。

如果您想要alpha频道和混合支持,则需要:AlphaBlend

您可以执行以下操作:

BLENDFUNCTION fnc;
fnc.BlendOp = AC_SRC_OVER;
fnc.BlendFlags = 0;
fnc.SourceConstantAlpha = 0xFF;
fnc.AlphaFormat = AC_SRC_ALPHA;
//You need to create a memDC.. and an HBITMAP..
//Select the hBitmap into the memDC.
HGDIOBJ obj = SelectObject(memDC, hBmp);
//Render with alpha blending..
AlphaBlend(DC, rect.X, rect.Y, rect.Width, rect.Height, memDC, 0, 0, Width, Height, fnc);
//Restore the memDC to original state..
SelectObject(memDC, obj);

或通过自己计算频道的颜色来进行自己的预杀alpha渲染。

另外,您可以尝试GDI 并查看如何工作:

ULONG_PTR GdiImage::GDIToken = 0;
Gdiplus::GdiplusStartupInput GdiImage::GDIStartInput = NULL;
Gdiplus::GdiplusStartup(&GdiImage::GDIToken, &GdiImage::GDIStartInput, NULL);
Gdiplus::Image* Img = Gdiplus::Image::FromFile(L"PathToImage.ext"); //where ext can be png, bmp, etc..
Gdiplus::Graphics graphics(DC);
//graphics.SetSmoothingMode(SmoothingModeHighSpeed);
graphics.SetInterpolationMode(Gdiplus:: InterpolationModeBilinear); //InterpolationModeNearestNeighbor
//graphics.SetPixelOffsetMode(Gdiplus::PixelOffsetModeHalf);
graphics.DrawImage(Img, x, y, w, h);
delete Img;
Gdiplus::GdiplusShutdown(GdiImage::GDIToken);
GdiImage::GDIStartInput = NULL;
GdiImage::GDIToken = 0;

我尝试寻找可以提供任何一种的Winapi功能 功能,但我没有发现。

尽管其他人已经提出了一些建议,但据我所知

有许多可用于重采样的第三方库。如果图像处理不是您的应用程序的主要工作,那么其中许多(大多数?)很复杂,并且预计过大。

在下面的示例中,我使用的是公共域单头文件,无外部依赖性" stb_image_resize.h" 库。只需在您的项目中进行#include即可完成。图书馆不是最快的,但我不会特别慢。它闪耀的位置是易于使用和多功能性。如果您想拥有其他过滤器,例如 lanczos (如果有兴趣,我可以提供代码)也很容易扩展。尽管内置过滤器已经比OS API的过滤器要好得多。

以下示例程序希望在当前目录的文件" flower.bmp"中找到32 BPP位图,并带有Alpha-ennynel(非杂质)。使用OS API LoadImageW()加载图像,使用stbir_resize_uint8()重新采样至原始尺寸的三分之一,并使用GDI 。

#include <Windows.h>
#include <iostream>
#include <gdiplus.h>
#pragma comment( lib, "gdiplus" )
namespace gp = Gdiplus;
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#include "stb_image_resize.h"
int main()
{
    // Using LR_CREATEDIBSECTION flag to get direct access to the bitmap's pixel data. 
    HBITMAP hBmpIn = reinterpret_cast<HBITMAP>(
        LoadImageW( NULL, L"flower.bmp", IMAGE_BITMAP, 0, 0, 
                    LR_LOADFROMFILE | LR_CREATEDIBSECTION ) );
    if( !hBmpIn )
    {
        std::cout << "Failed to load bitmap.n";
        return 1;
    }
    // Getting bitmap information including a pointer to the bitmap's pixel data 
    // in infoIn.dsBm.bmBits.
    // This will fail if hBmpIn is not a DIB. In this case you may call GetDIBits() 
    // to get a copy of the bitmap's pixel data instead.
    DIBSECTION infoIn{};
    if( !GetObject( hBmpIn, sizeof( infoIn ), &infoIn ) )
    {
        std::cout << "Bitmap is not a DIB.n";
        return 1;
    }
    // Some sanity checks of the input image.
    if( infoIn.dsBm.bmBitsPixel != 32 || infoIn.dsBm.bmPlanes != 1 ||
        infoIn.dsBmih.biCompression != BI_RGB )
    {
        std::cout << "Bitmap is not 32 bpp uncompressed.n";
        return 1;
    }
    // Create a DIB for the output. We receive a HBITMAP aswell as a writable 
    // pointer to the bitmap pixel data.
    int out_w = infoIn.dsBm.bmWidth / 3, out_h = infoIn.dsBm.bmHeight / 3;
    BITMAPINFO infoOut{};
    auto& hdr = infoOut.bmiHeader;
    hdr.biSize = sizeof(hdr);
    hdr.biBitCount = 32;
    hdr.biCompression = BI_RGB;
    hdr.biWidth = out_w;
    hdr.biHeight = out_h;  // negate the value to create top-down bitmap
    hdr.biPlanes = 1;
    unsigned char* pOutPixels = nullptr;
    HBITMAP hBmpOut = CreateDIBSection( NULL, &infoOut, DIB_RGB_COLORS, 
        reinterpret_cast<void**>( &pOutPixels ), NULL, 0 );
    if( !hBmpOut )
    {
        std::cout << "Could not create output bitmap.n";
        return 1;
    }
    // Resample the input bitmap using the simplest API. 
    // These functions use a "default" resampling filter defined at compile time 
    // (currently "Mitchell" for downsampling and "Catmull-Rom" for upsampling). 
    // To change the filter, you can change the compile-time defaults 
    // by #defining STBIR_DEFAULT_FILTER_UPSAMPLE and STBIR_DEFAULT_FILTER_DOWNSAMPLE, 
    // or you can use the medium-complexity API.
    // Consult "stb_image_resize.h" which contains the documentation.
    stbir_resize_uint8( 
        reinterpret_cast< unsigned char const* >( infoIn.dsBm.bmBits ), 
        infoIn.dsBm.bmWidth,
        infoIn.dsBm.bmHeight,
        0,  // input_stride_in_bytes, 0 = packed continously in memory
        pOutPixels,
        out_w,
        out_h,
        0,  // output_stride_in_bytes, 0 = packed continously in memory
        4   // num_channels
    );
    // Use GDI+ for saving the resized image to disk.
    gp::GdiplusStartupInput gdiplusStartupInput;
    ULONG_PTR gdipToken = 0;
    gp::GdiplusStartup( &gdipToken, &gdiplusStartupInput, nullptr );
    {
        gp::Bitmap bmpOut( hBmpOut, nullptr );
        // I'm taking a shortcut here by hardcoding the encoder CLSID. Check MSDN to do it by-the-book:
        // https://msdn.microsoft.com/en-us/library/windows/desktop/ms533843(v=vs.85).aspx
        class __declspec(uuid("{557cf400-1a04-11d3-9a73-0000f81ef32e}")) BmpEncoderId;
        bmpOut.Save( L"flower_resized.bmp", &__uuidof(BmpEncoderId) );
    }
    // Cleanup
    gp::GdiplusShutdown( gdipToken );
    DeleteObject( hBmpIn );
    DeleteObject( hBmpOut );
    std::cout << "All done.n";
    return 0;
}

注意:

重新采样透明的图像时,通常建议使用前alpha通道。否则,重新采样的图像可以具有伪影,通常沿形状边缘值得注意。除非您指定STBIR_FLAG_ALPHA_PREMULTIPLIED标志,否则Stbir将使用" Alpha加权重新采样"(有效进行预列,重新采样,然后取消促进)。因此,加载图像后,手动进行一次预制时,您将获得性能好处。大多数可以显示透明图像的Windows API(例如AlphaBlend),无论如何都期望alpha频道进行体验。