9

I am currently trying to save a bitmap image, but the background is changing to black.

I can "Save As" the image perfectly fine. I can also "Save" the image as well. Which was much more difficult because I had to overwrite the existing image.

However, when I "save" my image the background is turning black. And I have no idea what is causing it.

Here is my code:

Bitmap tempImage = new Bitmap(DrawArea);

DrawArea.Dispose();

if (extension == ".jpeg")
    tempImage.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
else
    tempImage.Save(fileName, System.Drawing.Imaging.ImageFormat.Bmp);

DrawArea = new Bitmap(tempImage);
pictureBox1.Image = DrawArea;

tempImage.Dispose();
Johnrad
  • 2,637
  • 18
  • 58
  • 98
  • See http://stackoverflow.com/questions/4067448/converting-image-to-bitmap-turns-background-black or http://stackoverflow.com/questions/6513633/c-sharp-converting-transparent-png-to-jpg-black-background – Mark Ransom Nov 29 '11 at 20:08

2 Answers2

26

Create a blank bitmap. Create a graphics object to write on with that blank bitmap. Clear the bitmap and change its color to white. Then draw the image then save the bitmap.

            Bitmap blank = new Bitmap(DrawArea.Width, DrawArea.Height);
            Graphics g = Graphics.FromImage(blank);
            g.Clear(Color.White);
            g.DrawImage(DrawArea, 0, 0, DrawArea.Width, DrawArea.Height);

            Bitmap tempImage = new Bitmap(blank);
            blank.Dispose();
            DrawArea.Dispose();

            if (extension == ".jpeg")
                tempImage.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
            else
                tempImage.Save(fileName, System.Drawing.Imaging.ImageFormat.Bmp);

            DrawArea = new Bitmap(tempImage);
            pictureBox1.Image = DrawArea;

            tempImage.Dispose();
Johnrad
  • 2,637
  • 18
  • 58
  • 98
  • 3
    Nice to see my super old question could help someone. – Johnrad Apr 21 '14 at 01:58
  • your solution is used(up voted), but how g.save() happens here? I created a new bitmap, new graphics(bitmap) , adding all content then bitmap.save, here how graphics content is pushed to bitmap? – Pranesh Janarthanan May 02 '16 at 09:11
2

Try to save the image in PNG format rather than JPEG..

Vishwas
  • 49
  • 2