即使将Bitmap设置为Graphics.Clear(Color.Transparent),为什么我在调整大小时会在图像周围出现黑色背景

时间:2011-03-08 00:51:43

标签: c# image-processing background gdi+ transparency

我正在构建一个图像上传工具,可以调整图像大小以适应固定大小,但它会在图像周围的填充空间中添加黑色背景而不是透明背景。

我已经读过需要将Bitmap设置为带有Alpha图层的PixelFormat,并且我可以将Graphics clear颜色设置为透明但我仍然遇到同样的问题。

我的照片大多是jpeg。这是代码:

private void ResizeImage(Image Original, Int32 newWidth, Int32 newHeight, String pathToSave)
    {
        int sourceX = 0;
        int sourceY = 0;
        int destX = 0;
        int destY = 0;

        int originalWidth = Original.Width;
        int originalHeight = Original.Height;
        float nPercent = 0;
        float nPercentW = 0;
        float nPercentH = 0;

        nPercentW = ((float)newWidth / (float)originalWidth);
        nPercentH = ((float)newHeight / (float)originalHeight);

        if (nPercentH < nPercentW)
        {
            nPercent = nPercentH;
            destX = System.Convert.ToInt16((newWidth -
                          (originalWidth * nPercent)) / 2);
        }
        else
        {
            nPercent = nPercentW;
            destY = System.Convert.ToInt16((newHeight -
                          (originalHeight * nPercent)) / 2);
        }

        int destWidth = (int)(originalWidth * nPercent);
        int destHeight = (int)(originalHeight * nPercent);


        Bitmap bmp = new Bitmap(newWidth, newHeight, PixelFormat.Format32bppArgb);

            bmp.SetResolution(Original.HorizontalResolution, Original.VerticalResolution);
            using (Graphics Graphic = Graphics.FromImage(bmp))
            {
                Graphic.CompositingQuality = CompositingQuality.HighQuality;
                Graphic.Clear(Color.Red);
                Graphic.CompositingMode = CompositingMode.SourceCopy;
                Graphic.SmoothingMode = SmoothingMode.AntiAlias;
                Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;

                Graphic.DrawImage(
                    Original,
                    new Rectangle(destX, destY, destWidth, destHeight),
                    new Rectangle(sourceX, sourceY, originalWidth, originalHeight),
                    GraphicsUnit.Pixel
                    );

                bmp.Save(pathToSave,Original.RawFormat);

            }

}

2 个答案:

答案 0 :(得分:5)

          Graphic.Clear(Color.Red);

不,你把背景变成了红色,而不是黑色。如果要将背景的alpha设置为0,请使用Color.Transparent。或者只省略Clear(),它是新位图的默认值。并且在Save()调用中避免使用Original.RawFormat,您不希望使用不支持透明度的图像格式。 Png总是很好。并确保您用于显示结果位图的任何方法都支持透明度。具有明确定义的背景颜色。如果没有,你会变黑,Color.Transparent有R,G和B为0.黑色。

答案 1 :(得分:1)

图片的输入格式是什么?如果它是jpg,那可能是因为jpg不支持透明度。您可以尝试使用支持透明度的PNG输出格式:

bmp.Save(pathToSave, ImageFormat.Png);