MrGreyKnight
MrGreyKnight

Reputation: 37

C# getting unusable base64 when converting from bitmap

I'm trying to capture the screen and then output the screenshot as a base64 image but cannot seem to get a usable base64 image out my code.

public static Bitmap bitmap;
    public static string base64;
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        CaptureScreen();
        Graphics graphics = Graphics.FromImage(bitmap as Image);
        graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
        pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
        pictureBox1.Image = bitmap;
        richTextBox1.Text = base64;
    }
    public static string CaptureScreen()
    {
        bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
        Bitmap bImage = bitmap;
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        bImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        byte[] byteImage = ms.ToArray();
        base64 = Convert.ToBase64String(byteImage);
        return base64;
    }

I get this output when testing and it should display this or close too this image.

Upvotes: 2

Views: 245

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062745

The problem here is timing.

You are creating the base-64 before you copy the screen into the image; you need to move the line:

graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);

to happen before the line:

bImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

Try literally just changing it to:

graphics.CopyFromScreen(0, 0, 0, 0, bImage.Size);
bImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

Upvotes: 2

Related Questions