开发者

Alpha channel transparency and resizing image files

I'm using the following code to resize a tif. The tif has an alpha channel set for transparency. I'm trying to resize this image and honour the transparency but at the moment it's coming out with a black background. Any ideas?

public static void ResizeImage(string OriginalImagePath, string NewImagePath, int Width, int Height)
        {
            Size开发者_C百科 NewSize = new Size(Width, Height);

            using (Image OriginalImage = Image.FromFile(OriginalImagePath))
            {
                //Graphics objects can not be created from bitmaps with an Indexed Pixel Format, use RGB instead.
                PixelFormat Format = OriginalImage.PixelFormat;
                if (Format.ToString().Contains("Indexed"))
                    Format = PixelFormat.Format24bppRgb;

                using (Bitmap NewImage = new Bitmap(NewSize.Width, NewSize.Height, OriginalImage.PixelFormat))
                {
                    using (Graphics Canvas = Graphics.FromImage(NewImage))
                    {
                        Canvas.SmoothingMode = SmoothingMode.AntiAlias;
                        Canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        Canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        Canvas.DrawImage(OriginalImage, new Rectangle(new Point(0, 0), NewSize));
                        NewImage.Save(NewImagePath, OriginalImage.RawFormat);
                    }
                }
            }
        }

    }


Try this:

if (Format.ToString().Contains("Indexed"))
    Format = PixelFormat.Format32bppArgb;

Format32bppArgb specifies an alpha channel in the pixel format.

And I think you meant to do this:

using (Bitmap NewImage = new Bitmap(NewSize.Width, NewSize.Height, Format))

EDIT:

Actually, try just forcing the pixel format on the NewImage to Format32bppArgb like so:

using (Bitmap NewImage = new Bitmap(NewSize.Width, NewSize.Height,
    PixelFormat.Format32bppArgb))


Canvas.Clear(Color.Transparent)

before you blit.


I actually found out that due to the way the transparency is stored in the tiff format with photoshop it was better to create png's by automating photoshop and then crunching off the resulting png.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜