【发布时间】:2017-12-23 21:10:41
【问题描述】:
我有以下代码,它可以正常工作,但是,它工作得非常慢,并且读取带有记录的文件并分析每个像素 - 这花费了太长时间。有什么办法可以让它更快地工作吗?
[DllImport("user32.dll")]
static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("user32.dll")]
static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);
[DllImport("gdi32.dll")]
static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);
static void Main(string[] args)
{
if (isCorrect("test.LOB"))
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("Nope...");
}
Console.ReadKey();
//Record("test", 0, 0, 50, 50, 10);
}
public static void Record(string name, int start_x, int start_y, int end_x, int end_y, int max_Difference)
{
string path = name + ".LOB";
string result;
Color pixel_Result;
for (int x = start_x; x <= end_x; x++)
{
for (int y = start_y; y <= end_y; y++)
{
pixel_Result = GetPixelColor(x, y);
result = x + "|" + y + "|" + pixel_Result.R + "|" + pixel_Result.G + "|" + pixel_Result.B + "|" + max_Difference;
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(result);
}
}
else
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(result);
}
}
}
}
}
public static bool isCorrect(string path)
{
using (StreamReader sr = File.OpenText(path))
{
string result = "";
string[] correctedResult;
while ((result = sr.ReadLine()) != null)
{
correctedResult = result.Split('|');
int X = Convert.ToInt32(correctedResult[0]);
int Y = Convert.ToInt32(correctedResult[1]);
int R = Convert.ToInt32(correctedResult[2]);
int G = Convert.ToInt32(correctedResult[3]);
int B = Convert.ToInt32(correctedResult[4]);
int maxDifference = Convert.ToInt32(correctedResult[5]);
Color c;
c = GetPixelColor(X, Y);
maxDifference /= 2;
if (R < c.R - maxDifference || R > c.R + maxDifference)
{
return false;
}
if (G < c.G - maxDifference || G > c.G + maxDifference)
{
return false;
}
if (B < c.B - maxDifference || B > c.B + maxDifference)
{
return false;
}
}
return true;
}
}
static public Color GetPixelColor(int x, int y)
{
IntPtr hdc = GetDC(IntPtr.Zero);
uint pixel = GetPixel(hdc, x, y);
ReleaseDC(IntPtr.Zero, hdc);
Color color = Color.FromArgb((int)(pixel & 0x000000FF),
(int)(pixel & 0x0000FF00) >> 8,
(int)(pixel & 0x00FF0000) >> 16);
return color;
}
提前致谢!
【问题讨论】:
-
好的,不用进入不安全的方法,马上我看到你正在记录每个循环!最重要的是,您每次都在创建一个新的流作家。
-
你能告诉我们
GetDC、GetPixel和ReleaseDC -
我尝试将它包含在上面的代码中,但由于某种原因它不断破坏帖子... [DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr hwnd); [DllImport("user32.dll")] static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc); [DllImport("gdi32.dll")] static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);
-
该死,让我再试一次。
-
您需要突出显示文本并单击帖子工具栏上的按钮
{ }。您不能将代码放入 cmets。
标签: c# file file-io streamreader streamwriter