简体   繁体   中英

Saving an image bmp c#

I have this function that draw an image in bmp format

private void DrawImage(Byte[] imgData, PictureBox picBox)
  {
     int colorval;
     Bitmap bmp = new Bitmap(m_ImageWidth, m_ImageHeight);
     picBox.Image = (Image)bmp;

     for (int i=0; i<bmp.Width; i++)
     {
        for (int j=0; j<bmp.Height; j++)
        {
           colorval = (int)imgData[(j*m_ImageWidth)+ i];
           bmp.SetPixel(i,j,Color.FromArgb(colorval,colorval, colorval));
        }
     }
     picBox.Refresh();

    }

When i add picBox.Image.Save(@"C:\\Users\\Jose Moreno\\Desktop", System.Drawing.Imaging.ImageFormat.Bmp);

below PicBox.Refresh();, the program crash with the errror: "An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll"

Why the program crash? thatks for the help.

Image.Save(String, ImageFormat) requires the full filename , not just the file path . "C:\\Users\\Jose Moreno\\Desktop" is (presumably) the name of a pre-existing directory, not the name of a file that could be created. You need to pass an actual file name, for instance:

picBox.Image.Save(@"C:\Users\Jose Moreno\Desktop\TestFilename.bmp", System.Drawing.Imaging.ImageFormat.Bmp);

If a file of the specified name cannot be created, you will get this inscrutable error.

Note that if the image was originally loaded from a file, you cannot save back to the same file until the image is disposed of because the file gets locked. See How can I fix this GDI+ generic exception when I save images? . But that's not the problem shown in your question.

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