从位图转换时 C# 获取不可用的 base64

C# getting unusable base64 when converting from bitmap

我正在尝试捕获屏幕,然后将屏幕截图输出为 base64 图像,但似乎无法从我的代码中获取可用的 base64 图像。

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

我得到 this output when testing and it should display this or close too this 图片。

这里的问题是时机。

您在将屏幕复制到图像中之前创建 base-64 ;你需要移动这条线:

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

之前发生:

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

试着把它改成:

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