C#转换屏幕截图数据 [英] C# convert screenshot data
问题描述
如果不保存,我需要截取屏幕截图。我会将图像数据直接发送到PHP脚本。因为我目前没有这个PHP脚本,所以我搜索最简单的格式,我应该转换截图数据。出于调试原因,在我获得PHP脚本之前,我想使用C#在客户端转换这些数据的图片。
I would need to take a screenshot, if easy to without saving it. I would sent the image data directly to a PHP script. Because I don't have this PHP script at the moment, so I search for the easiest way of format in which I should convert the screenshot data. For debugging reasons until I've got my PHP script I would like to convert a picture of these data on my client side using C#.
我的代码截图并转换它(我不确定我是否可以将我的日志文件中的输出转换回图片):
My code at the moment for taking a screenshot and convert it (I'm not sure if I can convert the output in my logfile back into a picture):
internal static byte[] ImageToByteArray(Image img)
{
byte[] byteArray = new byte[0];
MemoryStream stream = new MemoryStream();
img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Close();
byteArray = stream.ToArray();
return byteArray;
}
public static string TakeScreenshot()
{
String filepath = @"C:\log2.txt";
Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
graphics.Dispose();
bitmap.Save("C:\\temp.png");
Image img = (Image)bitmap;
string str = System.Text.Encoding.Default.GetString(ImageToByteArray(img));
System.IO.File.AppendAllText(filepath, str);
//just for debugging
return "OH";
}
目前的主要问题是,有什么方法可以从我的转换代码(log2.txt)。
Main question at the moment, is there any way to get a picture back from my converted code (log2.txt).
推荐答案
这行代码:
string str = System.Text.Encoding.Default.GetString(ImageToByteArray(img));
几乎肯定不会做你想做的事。它将尝试将您的字节数组解释为机器上默认字符编码的字符串。如果默认值类似于UTF-8或任何多字节字符集,那么它很可能会失败。即使默认编码是单字节字符集,它也可能会创建一个无法可靠地转回原始字节数组的字符串。
Will almost certainly not do what you want it to do. It will try to interpret your byte array as a string in whatever is the default character encoding on your machine. If the default is something like UTF-8 or any multibyte character set, then it's quite likely to fail. Even if the default encoding is a single-byte character set, it could create a string that can't be reliably turned back into the original byte array.
如果你真的想要将字节数组存储为文本,可以调用 Convert.ToBase64String :
If you really want to store the byte array as text, you can call Convert.ToBase64String:
string str = Convert.ToBase64String(ImageToByteArray(img));
如果从文件中读回该字符串到 str
,你可以用以下代码重建字节数组:
If you read that string back from the file into str
, you can rebuild the byte array with:
byte[] imageBytes = Convert.FromBase64String(str);
在特定情况下的另一个优点是有PHP函数可以处理base 64字符串。
Another advantage in your particular case is that there are PHP functions for dealing with base 64 strings.
这篇关于C#转换屏幕截图数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!