简体   繁体   English

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

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

I'm trying to write a program in c# to send a frame via ethernet. 我正在尝试用C#编写程序以通过以太网发送帧。

Currently I have .jpg test images in 1920x1080 resolution and very different sizes in bytes. 目前,我有1920x1080分辨率的.jpg测试图像,并且字节大小非常不同。

I am trying to convert a .jpg image to a byte array, I looked for similar answers but when I tried them I got byte arrays including 437, 1030, 1013 bytes for each image. 我试图将.jpg图像转换为字节数组,我寻求类似的答案,但是当我尝试它们时,我得到了每个图像包括437、1030、1013字节的字节数组。 Considering that the images are in HD resolution, this does not make sense. 考虑到图像为高清分辨率,这没有意义。 How can I convert an image file to form a 1920*1080*3 (RGB) byte array? 如何将图像文件转换为1920 * 1080 * 3(RGB)字节数组? Please keep in mind that I am trying to develop a real time application that should be able to send frames at a high rate so this code cannot be slow. 请记住,我正在尝试开发一个实时应用程序,该应用程序应该能够以高速率发送帧,因此此代码不会太慢。

Thanks in advance. 提前致谢。 Tunc unc

to read Image bytes to byte array: 读取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();

to create image from byte array: 从字节数组创建图像:

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

JPG is a compressed format, that's why its size (and size of the corresponding Byte array) will be usually far less than 1920*1080*3. JPG是一种压缩格式,因此其大小(和相应的Byte数组的大小)通常通常远远小于1920 * 1080 * 3。 In order to get Byte array from JPG you can use streams: 为了从JPG获取字节数组,您可以使用流:

  Image myImage; 
  ...
  byte[] result;

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

    result = ms.ToArray();
  }

If all you want are pixels in a form of Byte array you have to convert your JPG into BMP (or other raw, uncompressed format) 如果您想要的只是字节数组形式的像素,则必须将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