简体   繁体   English

GDI透明背景C#

[英]GDI Transparent Background C#

I am using windows GDI Library to resize the image using the following code. 我正在使用Windows GDI库使用以下代码来调整图像的大小。 I am trying to generate the transparent images. 我正在尝试生成透明图像。 This function is called from from and function that generates images. 从中调用此功能,并从中生成图像。 If I save the image without resizing I am getting transparency 如果我保存图像而没有调整大小,我将获得透明度

    static Image FixedSize(Image imgPhoto, int Width, int Height)
    {
        int sourceWidth = imgPhoto.Width;
        int sourceHeight = imgPhoto.Height;
        int sourceX = 0;
        int sourceY = 0;
        int destX = 0;
        int destY = 0; 

        float nPercent = 0;
        float nPercentW = 0;
        float nPercentH = 0;

        nPercentW = ((float)Width/(float)sourceWidth);
        nPercentH = ((float)Height/(float)sourceHeight);
        if(nPercentH < nPercentW)
        {
            nPercent = nPercentH;
            destX = System.Convert.ToInt16((Width - 
                          (sourceWidth * nPercent))/2);
        }
        else
        {
            nPercent = nPercentW;
            destY = System.Convert.ToInt16((Height - 
                          (sourceHeight * nPercent))/2);
        }

        int destWidth  = (int)(sourceWidth * nPercent);
        int destHeight = (int)(sourceHeight * nPercent);

        Bitmap bmPhoto = new Bitmap(Width, Height, 
                          PixelFormat.Format24bppRgb);
        bmPhoto.SetResolution(imgPhoto.HorizontalResolution, 
                         imgPhoto.VerticalResolution);

        Graphics grPhoto = Graphics.FromImage(bmPhoto);
        grPhoto.Clear(Color.Transparent);
        grPhoto.InterpolationMode = 
                InterpolationMode.HighQualityBicubic;

        grPhoto.DrawImage(imgPhoto, 
            new Rectangle(destX,destY,destWidth,destHeight),
            new Rectangle(sourceX,sourceY,sourceWidth,sourceHeight),
            GraphicsUnit.Pixel);

        grPhoto.Dispose();
fileName= txtImgName.text();
        bitmap.Save(Server.MapPath("~/images32/") + fileName, ImageFormat.Png);
    }

I am getting the image resized but the problem is that it is having black background. 我正在调整图像的大小,但问题是它具有黑色背景。 Please help me in generating Transparent Image 请帮助我生成透明图像

Thanks in Advance 提前致谢

I guess that is because you use a bitmap with RGB colors ( Format24bppRgb ) as source. 我猜这是因为您使用了具有RGB颜色( Format24bppRgb )的位图作为源。

Use one that contains an alpha channel, such as Format32bppArgb . 使用包含alpha通道的通道,例如Format32bppArgb

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM