简体   繁体   中英

Background Turns Black When Saving Bitmap - C#

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

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

尝试以PNG格式而不是JPEG格式保存图像。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM