簡體   English   中英

將ushort圖像轉換為二進制?

[英]Convert ushort image to binary?

我在 ushort 變量中有一個圖像,想以二進制格式保存這個圖像。

請任何人告訴我如何使用 C# 做到這一點?

我試過這個,但它不工作

ushort[] Depthdata;
Depthdata = new ushort[DWidth * DHeight];
string s1 = string.Format("{0}", count_depth);
FileStream fs = new FileStream("C:\\img" + s1 + ".bin", FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
string image_str = Convert.ToString(Imagedata);
bw.Write(image_str);
bw.Close();
fs.Close();

這是我的完整代碼

我想提一下,這里的代碼和您鏈接中的代碼不同......

無論如何,通過鏈接中的那個:

ushort[] Depthdata;
....
string s1 = string.Format("{0}", count_depth);
FileStream fs = new FileStream("G:\\test" + s1 + ".bin", FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
string depth_str = Convert.ToString(Depthdata);
bw.Write(depth_str);
bw.Close();
fs.Close();

您實際上不需要將 Depthdata 轉換為字符串。 BinaryWriter 實際上可以在其重載之一中采用ushort 值 為什么不只是迭代並寫出來呢? 此外,您應該對文件流和二進制編寫器使用using 語句

請嘗試以下操作:

using(FileStream fs = new FileStream("G:\\test" + s1 + ".bin", FileMode.Create, FileAccess.Write))
{
    using(BinaryWriter bw = new BinaryWriter(fs))
    {
        foreach(ushort value in Depthdata)
        {
            bw.write(value);
        }
    }
}

我認為這會幫助你。我在 *.tiff 文件上測試了這個

首先制作單獨的 Class Ext

public static class Ext
    {

        public static string ToHexString(this byte[] hex)
        {
            if (hex == null) return null;
            if (hex.Length == 0) return string.Empty;

            var s = new StringBuilder();
            foreach (byte b in hex)
            {
                s.Append(b.ToString("x2"));
            }
            return s.ToString().ToUpper();
        }
    }

然后您可以添加以下代碼將圖像轉換為字符串二進制

 FileStream fs=new FileStream(ImgPathID, FileMode.Open, FileAccess.Read); //set file stream
 Byte[] bindata=new byte[Convert.ToInt32(fs.Length)];
 fs.Read(bindata, 0, Convert.ToInt32(fs.Length));
string  bindatastring = Ext.ToHexString(bindata);// call to class

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM