[英]Convert ushort image to binary?
I have an image in ushort variable, want to save this image in binary format.我在 ushort 变量中有一个图像,想以二进制格式保存这个图像。
Please, anyone, tell me How can this be done using C#?请任何人告诉我如何使用 C# 做到这一点?
I have tried this but its not working我试过这个,但它不工作
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();
I would like to mention that the code here, and the one in your link are different...我想提一下,这里的代码和您链接中的代码不同......
In any case, going by the one in your link:无论如何,通过链接中的那个:
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();
You shouldn't actually need to convert your Depthdata to a string.您实际上不需要将 Depthdata 转换为字符串。 BinaryWriter can actually take a ushort value in one of its overloads. BinaryWriter 实际上可以在其重载之一中采用ushort 值。 Why not just iterate through and write it out?为什么不只是迭代并写出来呢? Also, you should use using statements for your filestream and binarywriter.此外,您应该对文件流和二进制编写器使用using 语句。
Try the following:请尝试以下操作:
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);
}
}
}
I think this will help you.i tested this on *.tiff file我认为这会帮助你。我在 *.tiff 文件上测试了这个
first make separate Class Ext首先制作单独的 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();
}
}
then you can Add following code to convert image to string binary然后您可以添加以下代码将图像转换为字符串二进制
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.