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

时间:2017-05-30 15:50:14

标签: c# .net string bitmap base64

我尝试捕获屏幕,然后将屏幕截图输出为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,它应显示此图像或关闭this图像。

1 个答案:

答案 0 :(得分:1)

这里的问题是时机。

您正在创建基础-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);