简体   繁体   中英

GDI Transparent Background C#

I am using windows GDI Library to resize the image using the following code. 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.

Use one that contains an alpha channel, such as Format32bppArgb .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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