[英]How to read pixel data of image in an ushort array and export this ushort array as a binary file in c#
[英]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.