简体   繁体   中英

Unable to save Bitmap Image with variable name

I am newbie in C#, Im trying to save a Bitmap image on button click. I am using visual studio 2010 for this. I am able to save my image with I pass a particular string as file name. here is my code for saving image:-

    private void button1_Click(object sender, EventArgs e)
    { 

        bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
        gfxScreenshot = Graphics.FromImage(bmpScreenshot);
        gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
        bmpScreenshot.Save("img.jpg", ImageFormat.Jpeg);
    }

But I want to save this image having name as time at which image was captured. So I add this in my code:-

    private void button1_Click(object sender, EventArgs e)
    { 
        string time = DateTime.Now.ToString("hh:mm:ss");
        string img = time + ".jpg";
        bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
        gfxScreenshot = Graphics.FromImage(bmpScreenshot);
        gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
        bmpScreenshot.Save(img, ImageFormat.Jpeg);

    }

This code build fine but when I click on my button, I got this exception:-

NotSupportedException was handled

Can anyone tell me how to save my image with name as timecode.

The name of the file should not consist : . Try to change that into underscore or simply remove it:

private void button1_Click(object sender, EventArgs e)
{ 
    string time = DateTime.Now.ToString("HHmmss");
    string img = time + ".jpg";
    bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
    gfxScreenshot = Graphics.FromImage(bmpScreenshot);
    gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
    bmpScreenshot.Save(img, ImageFormat.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