Tabish Saifullah
Tabish Saifullah

Reputation: 570

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.

Upvotes: 1

Views: 831

Answers (1)

Ian
Ian

Reputation: 30813

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

}

Upvotes: 2

Related Questions