[英]Exception on traveling through pixels BMP C#
Im using the following code to travel though the pixels of a BMP as this 我使用以下代码来通过BMP的像素
for (int i = 0; i <= Image.Width; i++)
{
for (int j = 0; j <= Image.Height; j++)
{
color = Image.GetPixel(i, j); //get
}
}
but im getting a exception 但我得到一个例外
System.ArgumentOutOfRangeException was unhandled
Message="Parameter must be positive and < Height.\r\nParameter name: y"
Source="System.Drawing"
ParamName="y"
I have no clue why im getting this.. im using a BMP
with valid heights and same code with hard-coded values working correctly 我不知道为什么我得到这个...我使用具有有效高度和相同代码与硬编码值正常工作的
BMP
@Odded @Odded
No:1 Shows what i needed and no 2 is whats happening with ur code any idea? No:1显示我需要的内容,没有2是你的代码有什么想法吗?
You have an off-by-one error in your loops. 循环中有一个off-by-one错误。
If the image Height
and Width
is 100, to get the "last" pixel you will need to call it as GetPixel(99,99)
. 如果图像
Height
和Width
为100,要获得“最后”像素,您需要将其称为GetPixel(99,99)
。
for (int i = 0; i < Image.Width; i++)
{
for (int j = 0; j < Image.Height; j++)
{
color = Image.GetPixel(i, j); //get
}
}
Just change Height and Width. 只需改变高度和宽度。 This is such an example of looking too far in your own code - this brings back so many memories..
这是一个在你自己的代码中看得太远的例子 - 这带回了这么多的回忆......
for(int i=0;i<BMP.Height;i++)
{
for(int j=0;j<BMP.Width;j++)
{
color = BMP.GetPixel(j,i);
}
}
Swap the two loops. 交换两个循环。
for(int j=0; j<BMP.Height; j++)
{
for(int i=0; i<BMP.Width; i++)
{
color = BMP.GetPixel(i,j);
}
}
Everyone is focusing on width and height, that's NOT the solution. 每个人都专注于宽度和高度,这不是解决方案。
GetPixel
takes two arguments, x
and y
. GetPixel
有两个参数, x
和y
。 The y
coordinate must be the outer loop to get the order you want. y
坐标必须是外部循环才能获得所需的顺序。
The x-coordinate always runs from 0
... Width-1
x坐标始终从
0
... Width-1
Flip your loops around. 翻转你的循环。 The outer loop should be the height and the inner loop should be the width if you want it to behave like the 1st image.
外部循环应该是高度,如果您希望它的行为与第一个图像相同,则内部循环应该是宽度。
Just swap around the Width and Height: 只需交换宽度和高度:
for(int i=0;i<BMP.Height;i++){
for(int j=0;j<BMP.Width;j++){
color=BMP.GetPixel(j, i);
}
}
I've also swapped around i
and j
so that GetPixel
works correctly 我还交换了
i
和j
以便GetPixel
正常工作
Let's make this simple and use x and y instead of i and j so it's easier to think about in Cartesian coordinates. 让我们简单一点,使用x和y代替i和j,这样在笛卡尔坐标系中更容易思考。
//For each height, loop through all pixels at that height.
for(int y=0; y < BMP.Height; y++)
{
for(int x=0; x < BMP.Width; x++)
{
color = BMP.GetPixel(x,y);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.