[英]Bitmap to Integer routine generating exception
public static bool IsGrayscale(Bitmap bitmap)
{
return bitmap.PixelFormat == PixelFormat.Format8bppIndexed ? true : false;
}
。
public static int[,] ToInteger(Bitmap image)
{
if (Grayscale.IsGrayscale(image))
{
Bitmap bitmap = (Bitmap)image.Clone();
int[,] array2d = new int[bitmap.Width, bitmap.Height];
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
ImageLockMode.ReadWrite,
PixelFormat.Format8bppIndexed);
int bytesPerPixel = sizeof(byte);
unsafe
{
byte* address = (byte*)bitmapData.Scan0;
int paddingOffset = bitmapData.Stride - (bitmap.Width * bytesPerPixel);
for (int i = 0; i < bitmap.Width; i++)
{
for (int j = 0; j < bitmap.Height; j++)
{
int iii = 0;
//If there are more than 1 channels...
//(Would actually never occur)
if (bytesPerPixel >= sizeof(int))
{
byte[] temp = new byte[bytesPerPixel];
//Handling the channels.
//PixelFormat.Format8bppIndexed == 1 channel == 1 bytesPerPixel == byte
//PixelFormat.Format32bpp == 4 channel == 4 bytesPerPixel == int
for (int k = 0; k < bytesPerPixel; k++)
{
temp[k] = address[k];
}
iii = BitConverter.ToInt32(temp, 0);
}
else//If there is only one channel:
{
iii = (int)(*address);
}
array2d[i, j] = iii;
address += bytesPerPixel;
}
address += paddingOffset;
}
}
bitmap.UnlockBits(bitmapData);
return array2d;
}
else
{
throw new Exception("Not a grayscale");
}
}
以下行中的異常:
iii = (int)(*address);
快速傅立葉Transform.exe中發生了類型為'System.AccessViolationException'的未處理異常
附加信息:嘗試讀取或寫入受保護的內存。 這通常表明其他內存已損壞。
該異常的原因是什么?
我該如何解決?
。
。
PS我正在使用以下PNG圖像:
您在循環bitmap.Width
bitmap.Height
誤認為bitmap.Width
。 您應該在外部循環的高度和內部循環的寬度上進行迭代,因為步幅代表整個寬度+圖像的偏移量。 然后,您可以基於行添加padding
,而不是為所遍歷的每行添加padding
。 所以
for (int i = 0; i < bitmap.Height; i++)
{
for (int j = 0; j < bitmap.Width; j++)
{
正在工作。 另外,您必須將數組訪問從array2d[i, j] = iii
array2d[j, i] = iii
為array2d[j, i] = iii
因為索引現在屬於圖像的另一個維度
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.