[英]Reading Pixels from an image byte array
I have a jpeg image. 我有一个jpeg图片。 I save this bitmapdata to a byte array.
我将此位图数据保存到字节数组。
This jpeg has a width of 100 and a height of 100. jpeg的宽度为100,高度为100。
I want to extract an image of Rectanlge(10,10,20,20); 我想提取Rectanlge(10,10,20,20)的图像;
Obviously, I can interact through this byte array but I am unsure how to relate the x,y pixels of what I want to this byte array. 显然,我可以通过此字节数组进行交互,但是我不确定如何将所需像素的x,y像素与此字节数组相关联。 I know that I have to use the stride and pixel size which is 4 as it is rgba.
我知道我必须使用4的步幅和像素大小,因为它是rgba。
I have this which was from this link cropping an area from BitmapData with C# . 我有这是从此链接使用C#从BitmapData裁剪区域的 。
Bitmap bmp = new Bitmap(_file);
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData rawOriginal = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);
int origByteCount = rawOriginal.Stride * rawOriginal.Height;
byte[] origBytes = new Byte[origByteCount];
System.Runtime.InteropServices.Marshal.Copy(rawOriginal.Scan0, origBytes, 0, origByteCount);
int BPP = 4;
int width = 20;
int height = 20;
int startX = 10;
int startY = 10;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width * BPP; j += BPP)
{
int origIndex = (startX * rawOriginal.Stride) + (i * rawOriginal.Stride) + (startY * BPP) + (j);
int croppedIndex = (i * width * BPP) + (j);
//copy data: once for each channel
for (int k = 0; k < BPP; k++)
{
croppedBytes[croppedIndex + k] = origBytes[origIndex + k];
}
}
}
But this: 但是这个:
int origIndex = (startX * rawOriginal.Stride) + (i * rawOriginal.Stride) + (startY * BPP) + (j);
I found is incorrect. 我发现不正确。
Does anyone know what value I should set here please? 有人知道我应该在这里设置什么值吗?
thanks 谢谢
Stride
is bytes per line (Y), you shouldn't multiply x
at any point by Stride
Stride
是每行的字节数(Y),您不应在任何点Stride
x
乘以Stride
int y = startY + i;
int x = startX;
int origIndex = y * rawOriginal.Stride + x * BPP;
When you're working with bitmap data, there are 2 important things to keep in mind: 使用位图数据时,有两点要记住:
so if you want to get the offset of a pixel, just use this formula: 因此,如果要获取像素的偏移量,请使用以下公式:
int offset = x * BPP + y * stride;
if you want to extract only a part of your bitmap you could just do this: 如果您只想提取位图的一部分,则可以执行以下操作:
int i = 0;
for(int y = startY; y < startY + height; y++)
{
for(int k = startX * bpp + y * stride; k < (startX + width) * bpp + y * stride; k++)
{
croppedBytes[i] = origBytes[k];
i++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.