好吧,我已经创建了两个程序。一个使用GetPixels,另一个使用LockBits。我的GetPixels程序如下..。
所指的条纹图片是200x200 jpg。

Stopwatch GetTime = new Stopwatch();
Bitmap img = new Bitmap("stripe.jpg");
GetTime.Start();
for (int i = 0; i < img.Width; i++)
{
for (int j = 0; j < img.Height; j++)
{
Color pixel = img.GetPixel(i, j);
output += " " + pixel;
}
}
GetTime.Stop();现在,这个读取大约20秒来处理这个图像并输出所有像素。很好,但理论上我的LockBits应该更快一些。我的LockBits代码是..。
Bitmap bmp = new Bitmap("stripe.jpg");
Rectangle bmpRec = new Rectangle(0, 0, bmp.Width, bmp.Height); //Creates Rectangle for holding picture
BitmapData bmpData = bmp.LockBits(bmpRec, ImageLockMode.ReadWrite, Pixels); //Gets the Bitmap data
IntPtr Pointer = bmpData.Scan0; //Scans the first line of data
int DataBytes = Math.Abs(bmpData.Stride) * bmp.Height; //Gets array size
byte[] rgbValues = new byte[DataBytes]; //Creates array
string Pix = " ";
Marshal.Copy(Pointer, rgbValues, 0, DataBytes); //Copies of out memory
bmp.UnlockBits(bmpData);
Stopwatch Timer = new Stopwatch();
pictureBox1.Image = bmp;
Timer.Start();
for (int p = 0; p < DataBytes; p++)
{
Pix += " " + rgbValues[p];
}
Timer.Stop();时间是37秒。现在我不明白为什么我花在洛克比上的时间比GetPixels长。
而且,我的输出文件在列出的位置上不匹配。就好像他们是不正常的。
这是一个需要解决的大问题,所以提前感谢大家阅读并试图解决我的问题。
发布于 2014-05-05 04:20:48
你有几个问题我看得出来。最大的问题是您的图像宽度为200,但在内存中,它的步幅是600 (对我来说--可能与您类似)。这意味着您正在写出更多的数据,因为您不会忽略每行400个填充像素。
其他问题:
// creates array)- -有些是误导性的(//Scans the first line of data -不,它返回一个指向已经加载的数据的指针)。下面的代码在我的机器上仅在几毫秒内完成。
Bitmap bmp = new Bitmap(@"d:\stripe.jpg");
//pictureBox1.Image = bmp;
Stopwatch Timer = new Stopwatch();
Rectangle bmpRec = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bmpData = bmp.LockBits(
bmpRec, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
IntPtr Pointer = bmpData.Scan0;
int DataBytes = Math.Abs(bmpData.Stride) * bmp.Height;
byte[] rgbValues = new byte[DataBytes];
Marshal.Copy(Pointer, rgbValues, 0, DataBytes);
bmp.UnlockBits(bmpData);
StringBuilder pix = new StringBuilder(" ");
Timer.Start();
for (int i = 0; i < bmpData.Width; i++)
{
for (int j = 0; j < bmpData.Height; j++)
{
// compute the proper offset into the array for these co-ords
var pixel = rgbValues[i + j*Math.Abs(bmpData.Stride)];
pix.Append(" ");
pix.Append(pixel);
}
}
Timer.Stop();
Console.WriteLine(Timer.Elapsed);https://stackoverflow.com/questions/23464339
复制相似问题