调整字节数组或灰度图像的大小
本文关键字:灰度图像 字节 字节数 数组 调整 | 更新日期: 2023-09-27 18:15:17
我想使用双三次/双二次插值将ByteArray
从[5x7]
调整为[241x301]
像素。因此,我试图将ByteArray
转换为像素格式Format16bppGrayScale
的Bitmap
。然后,我尝试将调整大小的Bitmap
转换回另一个ByteArray
。
不幸的是,GDI似乎不支持Format16bppGrayScale
格式的转换。我总是得到异常,如invalid argument
或out of memory
。我在谷歌上查询了这个问题,但我只发现了这个类似的问题,这建议使用第三方库或编写自己的代码来使用字节数组调整大小。
谁能建议一个方法来获得一个调整大小的字节数组?
下面的代码示例给出了一个System.ArgumentException
。
static void Main(string[] args)
{
byte[] resizedBitmap = resizeImage(new byte[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }, 241, 301);
}
public static Byte[] resizeImage(byte[,] matrix, int width, int height)
{
// Create Bitmap from ByteArray
Bitmap original;
unsafe
{
fixed (byte* intPtr = &matrix[0, 0])
{
original = new Bitmap(5, 7, 4, PixelFormat.Format16bppGrayScale, new IntPtr(intPtr));
}
}
// Resize the Bitmap and convert it back to a ByteArray
Image newImage = new Bitmap(241, 301);
using (Graphics g = Graphics.FromImage(newImage))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bicubic;
// Convert the Bitmap back to a ByteArray
Bitmap bmp = new Bitmap(241, 301, g);
BitmapData bmpData = bmp.LockBits(new Rectangle(new Point(), bmp.Size), ImageLockMode.ReadOnly, PixelFormat.Format16bppGrayScale);
byte[] dataAsBytes = new byte[bmpData.Stride * bmpData.Height];
System.Runtime.InteropServices.Marshal.Copy(bmpData.Scan0, dataAsBytes, 0, dataAsBytes.Length);
bmp.UnlockBits(bmpData);
return dataAsBytes;
}
}
你总是可以使用GDI+插值来执行大小调整:
Image original = new Bitmap(/* path to your 5x7 image */);
Image newImage = new Bitmap(241, 301);
using (Graphics g = Graphics.FromImage(newImage))
{
g.InterpolationMode = InterpolationMode.Bicubic;
g.DrawImage(original, new Rectangle(0, 0, newImage.Width, newImage.Height));
}