使用Graphics.DrawImage,将透明PNG图像的背景更改为黑色

时间:2017-01-14 08:21:00

标签: c# asp.net asp.net-web-api

我已经编写了这个方法来调整我的图像大小,但是我的透明PNG图像的返回图像具有黑色背景。 解决方案是什么?

我已尝试Bitmap.MakeTransparent()Graphics.Clear(),但无法解决我的问题。 我已经检查了所有相关问题,但无法找到有关我问题的有用答案。

public HttpResponseMessage ImageResizer(string path, int w,int h)
    {

        var imagePath = HttpContext.Current.Server.MapPath(path); 
        Bitmap image;
        try
        {
            image = (Bitmap)System.Drawing.Image.FromFile(imagePath);
        }
        catch
        {
            HttpResponseMessage hrm = new HttpResponseMessage();
            return hrm;
        }

        int originalWidth = image.Width;
        int originalHeight = image.Height;

        // New width and height based on aspect ratio
        int newWidth = w;
        int newHeight = h;

        // Convert other formats (including CMYK) to RGB.
        Bitmap newImage = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb);
        // Draws the image in the specified size with quality mode set to HighQuality
        using (Graphics graphics = Graphics.FromImage(newImage))
        {
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.SmoothingMode = SmoothingMode.AntiAlias;
            graphics.CompositingQuality = CompositingQuality.HighQuality;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

            using (var attribute = new ImageAttributes())
            {
                attribute.SetWrapMode(WrapMode.TileFlipXY);

                // draws the resized image to the bitmap
                graphics.DrawImage(image, new Rectangle(0, 0, newImage.Width, newImage.Height), new Rectangle(0, 0, originalWidth, originalHeight), GraphicsUnit.Pixel);
            }
        }
        // Get an ImageCodecInfo object that represents the PNG codec.
        ImageCodecInfo imageCodecInfo = this.GetEncoderInfo(ImageFormat.Png);

        // Create an Encoder object for the Quality parameter.
        Encoder encoder = Encoder.Quality;

        // Create an EncoderParameters object. 
        EncoderParameters encoderParameters = new EncoderParameters(1);

        // Save the image as a PNG file with quality level.
        EncoderParameter encoderParameter = new EncoderParameter(encoder, 10);
        encoderParameters.Param[0] = encoderParameter;
        var splitPath = imagePath.Split('.');
        string newPath = splitPath[0] + "ss5.png";
        newImage.Save(newPath, ImageFormat.Png);

        MemoryStream memoryStream = new MemoryStream();
        newImage.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
        HttpResponseMessage response = new HttpResponseMessage();
        response.Content = new ByteArrayContent(memoryStream.ToArray());
        response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
        response.Content.Headers.ContentLength = memoryStream.Length;
        return response;
    }

    private ImageCodecInfo GetEncoderInfo(ImageFormat format)
    {
        return ImageCodecInfo.GetImageDecoders().SingleOrDefault(c => c.FormatID == format.Guid);
    }

1 个答案:

答案 0 :(得分:1)

您在app.get('/getAllItems', function(req, res, next) { Item.find({}, function(err, items) { res.json(items.toObject()); // <-- use .toObject() or .toJSON() }); }); 构造函数中使用PixelFormat.Format24bppRgb。该格式将您的位图限制为3个通道:红色,绿色和蓝色。因此,您创建的位图不支持alpha(a.k.a。透明度),并且默认为纯黑色图像。当您在其中绘制具有透明度的图像时,该图像的alpha将被预先倍增或丢弃,具体取决于其格式。

如果您想以透明度保存新图片,则需要使用Bitmap声明:

PixelFormat.Format32bppArgb