我正在使用带有OPOS DirectIO命令的条形码设备在模式之间进行切换。
问题是当我使用设备捕获图像时,我得到了一个字节数组
(从设备规格中,我得到的图像是JPG格式的“ 752x480 GrayScale 256,16,2”),我找不到将其转换为(图像)的方法。
我尝试了以下代码
MemoryStream ms = new MemoryStream(scannedByteArray);
pictureBox1.Image = Image.FromStream(ms);
但是没有用。总是抛出“参数无效”异常。
也尝试过:
byte[] buffer = scannedByteArray;
var bitmap = new Bitmap(752, 480, PixelFormat.Format24bppRgb);
var bitmap_data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
Marshal.Copy(buffer, 0, bitmap_data.Scan0, buffer.Length);
bitmap.UnlockBits(bitmap_data);
和跨步的另一种方式:
Bitmap im = new Bitmap(752, 480, -752,
PixelFormat.Format8bppIndexed,
Marshal.UnsafeAddrOfPinnedArrayElement(scannedByteArray, 0));
我得到了不好的图像或颜色错误的图像。
我尝试了很多解决方案(如下所示),但是没有一个帮助
第一名:Byte Array to Image Conversion
2nd:How to convert image to byte array(在这里我试图做相反的解决方案,但没有用) 我已经花了3天的时间解决这个问题,但仍然不知道如何显示图像或保存图像。
注1:字节数组的大小是可变的(每次我捕获图像时得到的字节数组的大小都不同)
注2:我尝试将像素格式设置为24位,16位和8位,并且具有不同的跨度值,并且始终会显示不良或损坏的图像。
我尝试如下使用JpegBitmapDecoder:
JpegBitmapDecoder decoder = new JpegBitmapDecoder(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapsource = decoder.Frames[0];
Bitmap bitmap = new Bitmap(bitmapsource.PixelWidth, bitmapsource.PixelHeight);
Rectangle rec = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
BitmapData bitmapdata = bitmap.LockBits(rec, ImageLockMode.WriteOnly,
(bitmapsource.Format.BitsPerPixel == 24 ? System.Drawing.Imaging.PixelFormat.Format24bppRgb : System.Drawing.Imaging.PixelFormat.Format32bppArgb));
bitmapsource.CopyPixels(System.Windows.Int32Rect.Empty, bitmapdata.Scan0, bitmapdata.Height * bitmapdata.Stride, bitmapdata.Stride);
bitmap.UnlockBits(bitmapdata);
,但第一行出现错误“没有适合该操作的成像组件”,我确信从设备接收的字节没有损坏,因为该设备在演示过程中没有任何问题,并且没有任何更改。其配置。
这是捕获图像时从设备获取的字节样本。
https://drive.google.com/file/d/1kBuLDMTe9snwin9voEJ7z6kr9QKizftf/view?usp=sharing
答案 0 :(得分:0)
你可以试试吗?
pictureBox1.Image = Image x = (Bitmap)((new ImageConverter()).ConvertFrom(scannedByteArray));