I'm copying an image. (My actual code is resizing the image but that's not relevant to my question.) My code looks something like this.
Image src = ...
using (Image dest = new Bitmap(width, height))
{
Graphics graph = Graphics.FromImage(dest);
graph.InterpolationMode = InterpolationMode.HighQualityBicubic;
graph.DrawImage(src, 0, 0, width, height);
dest.Save(filename, saveFormat);
}
This seems to work great unless src
is loaded from an image with transparencies (such as GIF) or an alpha channel (such as PNG).
How can I get DrawImage()
to transfer the transparencies/alpha channel to the new image, and then keep them when I save the file?
saveFormat
variable? It should bePixelFormat.Format32bppArgb
(or another format with alpha channel handled). Try also:using (Image dest = new Bitmap(width, height, PixelFormat.Format32bppArgb))
. – LoosesaveFormat
will vary depending on the format of the input file. If the input file does not support alpha channel, then it's safe to assume the image will not contain alpha channel pixels. – AmbitsaveFormat
for GIF files then:)? – LooseImageFormat.Gif
. – Ambitusing (Image dest = new Bitmap(src, width, height))
. This makes the image compatible with the source image. As with your recommendation, this supports alpha channels but not, unfortunately, GIF transparencies. – Ambitif (saveFormat == ImageFormat.Gif && src.Palette.Entries.Length > 0) { System.Drawing.Color firstColor = src.Palette.Entries[0]; src.Palette.Entries[0] = System.Drawing.Color.FromArgb(0, firstColor); }
before file saving. – Loosesrc.Palette.Entries.CopyTo(dest.Palette.Entries, 0);
– Spruik