如何在C#中将图像保存为8位?

时间:2016-06-15 09:03:39

标签: c# image-processing visual-studio-2015

我使用以下代码加载图片:

OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Select a Picture";
ofd.InitialDirectory = @"PATH";
if (ofd.ShowDialog() == DialogResult.OK)
{
      HostImageLocationTxt.Text = ofd.FileName;
      hostImage.Image = new Bitmap(ofd.FileName);
}

然后,我将图像加载到另一个" PictureBox"并使用以下代码保存图像而不进行任何修改:

if (transformedImage.Image != null)
            {
                Bitmap bmp = new Bitmap(transformedImage.Image);
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Title = "Select Save Location";
                sfd.InitialDirectory = @"PATH";
                sfd.AddExtension = true;
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    switch (Path.GetExtension(sfd.FileName).ToUpper())
                    {
                        case ".BMP":
                            bmp.Save(sfd.FileName, ImageFormat.Bmp);
                            break;
                        case ".gif":
                            bmp.Save(sfd.FileName, ImageFormat.Gif);
                            break;
                        case ".JPG":
                            bmp.Save(sfd.FileName, ImageFormat.Jpeg);
                            break;
                        case ".JPEG":
                            bmp.Save(sfd.FileName,ImageFormat.Jpeg);
                            break;
                        case ".PNG":
                            bmp.Save(sfd.FileName, ImageFormat.Png);
                            break;
                        case ".png":
                            bmp.Save(sfd.FileName, ImageFormat.Png);
                            break;
                        default:
                            break;
                    }
                }
            } 

保存的图像会产生不同的位深度(左:第一个加载图像,右图:保存的图像): Left: First Load Image , Right: Saved Image

如何使用第一个加载的相同格式保存它?谢谢。

1 个答案:

答案 0 :(得分:1)

你应该使用这个构造函数:

Bitmap Constructor (Int32, Int32, PixelFormat)

public Bitmap(
    int width,
    int height,
    PixelFormat format
)

并将其用于像素格式参数:System.Drawing.Imaging.PixelFormat.Format24bppRgb

修改

您可以使用它来转换您的图片(https://stackoverflow.com/a/2016509/5703316):

Bitmap orig = new Bitmap(@"path");
Bitmap clone = new Bitmap(orig.Width, orig.Height,
    System.Drawing.Imaging.PixelFormat.Format24bppRgb);

using (Graphics gr = Graphics.FromImage(clone)) {
    gr.DrawImage(orig, new Rectangle(0, 0, clone.Width, clone.Height));
}