简体   繁体   English

如何在ushort数组中读取图像的像素数据并将此ushort数组导出为c#中的二进制文件

[英]How to read pixel data of image in an ushort array and export this ushort array as a binary file in c#

i have one Tiff image it is an 16 bit image, now i want to read the pixel data as ushort array and stored it to binary format in text file. 我有一个Tiff图像,它是一个16位图像,现在我想将像素数据读取为ushort数组,并将其存储为文本格式的二进制格式。

i have sample code. 我有示例代码。

// Load file meta data with FileInfo
        FileInfo fileInfo = new FileInfo(path + "output.tif");

            // The byte[] to save the data in
            byte[] data = new byte[fileInfo.Length];
            // Load a filestream and put its content into the byte[]
            using (FileStream fs = fileInfo.OpenRead())
            {
                fs.Read(data, 0, data.Length);
            }

          ushort[] result = Array.ConvertAll(data, b => (ushort)b);

but it is reading meta data, i want to read pixel data. 但是它正在读取元数据,我想读取像素数据。

You should definitely use an external library for handling tiff files. 您绝对应该使用外部库来处理tiff文件。 It is a complex file format which can contain more than one image, the image(s) can be compressed etc. So just reading the byte array is definitely not helping you getting the pixel values. 这是一种复杂的文件格式,可以包含多个图像,可以压缩图像等。因此,仅读取字节数组绝对不会帮助您获取像素值。 And even if it just contained the color values of the pixels, you still had to combine every two bytes for a 16 bit image. 即使它仅包含像素的颜色值,您仍然必须将每两个字节合并为一个16位图像。

In your sample code, you just convert bytes to ushorts, meaning that you precede the numbers with zeroes, which does not change the value. 在示例代码中,您只是将字节转换为ushorts,这意味着您在数字之前加零,这不会更改值。

First of all, an Image is already a binary. 首先,映像已经是二进制文件。

Here, I don't understand the purpose of explicitly converting an image to ushort array. 在这里,我不明白将图像显式转换为ushort数组的目的。 Apart from that, You can simply save all bytes of Tiff image to a text file like this: 除此之外,您可以简单地将Tiff图像的所有字节保存到文本文件中,如下所示:

File.WriteAllBytes(@"Text file path", File.ReadAllBytes(@"Tiff image file path"));

Then to read it back from the binary file you can simply read all bytes from the saved text file and using MemoryStream and save it back to image. 然后,要从二进制文件中读回它,您可以简单地从保存的文本文件中读取所有字节,并使用MemoryStream并将其保存回映像中。

using (Image image = Image.FromStream(new MemoryStream(File.ReadAllBytes(@"Text file path"))))
{
    image.Save(@"Path to save image", ImageFormat.Tiff);
}

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

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