我试图将Unicode字符串转换为C#中的图像.每次我运行它都会在这一行上出错
Image image = Image.FromStream(ms, true, true);
Run Code Online (Sandbox Code Playgroud)
说:ArgumentException未被用户代码处理.参数无效.任何想法为什么会这样?以下是该功能的其余部分.
public Image stringToImage(string inputString)
{
byte[] imageBytes = Encoding.Unicode.GetBytes(inputString);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true, true);
return image;
}
Run Code Online (Sandbox Code Playgroud)
Unicode不会对您需要表示图像的所有可能字节序列进行编码.
byte[]- > String- > byte[]是一个转换,对于许多给定的字节序列都不起作用.你必须在整个过程中使用一个byte [].
例如,如果您读取字节,将它们转换为UTF-16,那么字节序列可能会被丢弃为无效.以下是UTF-16中无效字节序列的示例.
代码点U + D800到U + DFFF [编辑] Unicode标准永久保留这些代码点值,用于引导和跟踪代理的UTF-16编码,并且它们永远不会被分配一个字符,所以没有理由编码他们.官方的Unicode标准说所有UTF表单,包括UTF-16,都不能编码这些代码点.
希望这可以帮助您:
public Bitmap stringToImage(string inputString)
{
byte[] imageBytes = Encoding.Unicode.GetBytes(inputString);
using (MemoryStream ms = new MemoryStream(imageBytes))
{
return new Bitmap(ms);
}
}
Run Code Online (Sandbox Code Playgroud)
取出写入 MemoryStream 的调用。接受字节数组的构造函数调用会自动将字节数组的内容放入流中。否则,您的流包含原始数据的 2 个副本。此外,对 Write 的调用会将流的位置保留在流的末尾,因此 FromStream 调用无法读取任何数据。
所以它会是:
public Image stringToImage(string inputString)
{
byte[] imageBytes = Encoding.Unicode.GetBytes(inputString);
// Don't need to use the constructor that takes the starting offset and length
// as we're using the whole byte array.
MemoryStream ms = new MemoryStream(imageBytes);
Image image = Image.FromStream(ms, true, true);
return image;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42726 次 |
| 最近记录: |