How do you Draw Transparent Image using System.Drawing?

前端 未结 4 1742
孤独总比滥情好
孤独总比滥情好 2020-12-17 19:02

I\'m trying to return a transparent GIF from an .aspx page for display within a web page. I am trying to get the image to have transparency, but I just keep getting Black be

4条回答
  •  再見小時候
    2020-12-17 19:35

    here is some code to have a gif (that already have transparency in it) transformed (supposed you want to resize it) in bitmap and then can be showed properly with it's transparency.

    imagePath = System.Web.HttpContext.Current.Request.MapPath(libraryPath + reqImageFile);
    System.Drawing.Image image = null;
    Bitmap resizedImage = null;
    
    if (reqWidth == 0) { reqWidth = image.Width; }
    if (reqHeight == 0) { reqHeight = image.Height; }
    image = System.Drawing.Image.FromFile(imagePath);
    reqWidth = image.Width;
    reqHeight = image.Height;
    
    //here is the transparency 'special' treatment
    resizedImage = new Bitmap(reqWidth, reqHeight, PixelFormat.Format8bppIndexed);
    ColorPalette pal = resizedImage.Palette;
    for (int i = 0; i < pal.Entries.Length; i++)
    {
           Color col = pal.Entries[i];
           pal.Entries[i] = Color.FromArgb(0, col.R, col.G, col.B);
    }
    resizedImage.Palette = pal;
    BitmapData src = ((Bitmap)image).LockBits(new Rectangle(0, 0, reqWidth, reqHeight),  ImageLockMode.ReadOnly, image.PixelFormat);
    BitmapData dst = resizedImage.LockBits(new Rectangle(0, 0, resizedImage.Width, resizedImage.Height),
    ImageLockMode.WriteOnly, resizedImage.PixelFormat);
    ((Bitmap)image).UnlockBits(src);
    resizedImage.UnlockBits(dst);
    

    Good luck !

    Grégoire Lafortune

提交回复
热议问题