Hamidreza Amini
Hamidreza Amini

Reputation: 11

Using Graphics.DrawImage , changes the background of my transparent PNG images , to black

I've write this method to resize my images, but the returned image for my transparent PNG images, has a black background. What is the solution?

I've tried Bitmap.MakeTransparent() and also Graphics.Clear() but couldn't solve my problem. I've checked all related questions, but couldn't find any useful answer to my question.

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);
    }

Upvotes: 1

Views: 3141

Answers (1)

Abion47
Abion47

Reputation: 24736

You are using PixelFormat.Format24bppRgb in your Bitmap constructor. That format is limiting your bitmap to 3 channels: red, green, and blue. Because of this, the bitmap you are creating doesn't support alpha (a.k.a. transparency) and will default to a solid black image. When you draw an image with transparency in it, the alpha of that image will either be pre-multiplied or discarded, depending on its format.

If you want to save your new image with transparency, you need to declare it with PixelFormat.Format32bppArgb:

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

Upvotes: 4

Related Questions