繁体   English   中英

将.jpg图像的像素值读取到字节数组中

[英]Reading the pixel values of a .jpg image into a byte array

我正在尝试用C#编写程序以通过以太网发送帧。

目前,我有1920x1080分辨率的.jpg测试图像,并且字节大小非常不同。

我试图将.jpg图像转换为字节数组,我寻求类似的答案,但是当我尝试它们时,我得到了每个图像包括437、1030、1013字节的字节数组。 考虑到图像为高清分辨率,这没有意义。 如何将图像文件转换为1920 * 1080 * 3(RGB)字节数组? 请记住,我正在尝试开发一个实时应用程序,该应用程序应该能够以高速率发送帧,因此此代码不会太慢。

提前致谢。 unc

读取Image字节到字节数组:

                Image image = ...;
                MemoryStream ms = new MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                if (ms.Length == 0)
                {
                    ms.Close();
                    throw new Exception("Bad Image File");
                }

                ms.Position = 0;
                byte[] baImageBytes = new byte[ms.Length];
                ms.Read(baImageBytes , 0, (int)ms.Length);
                ms.Close();

从字节数组创建图像:

byte[] baImageBytes =...
Image myImage = Image.FromStream(new MemoryStream(baImageBytes ));

JPG是一种压缩格式,因此其大小(和相应的Byte数组的大小)通常通常远远小于1920 * 1080 * 3。 为了从JPG获取字节数组,您可以使用流:

  Image myImage; 
  ...
  byte[] result;

  using (MemoryStream ms = new MemoryStream()) {
    myImage.Save(ms, ImageFormat.Jpeg); 

    result = ms.ToArray();
  }

如果您想要的只是字节数组形式的像素,则必须将JPG转换为BMP(或其他未压缩的原始格式)

  Bitmap myImage;
  ... 
  byte[] rgbValues = null;

  BitmapData data = myImage.LockBits(new Rectangle(0, 0, myImage.Width, myImage.Height), ImageLockMode.ReadOnly, value.PixelFormat);

  try {
    IntPtr ptr = data.Scan0;
    int bytes = Math.Abs(data.Stride) * myImage.Height;
    rgbValues = new byte[bytes];
    Marshal.Copy(ptr, rgbValues, 0, bytes);
  }
  finally {
    myImage.UnlockBits(data);
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM