在C#中从字符串转换为Image [英] Converting from string to Image in C#

查看:143
本文介绍了在C#中从字符串转换为Image的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Unicode字符串转换为C#中的图像。每次运行它都会在这一行出错。

I am trying to convert a Unicode string to an image in C#. Each time I run it I get an error on this line

Image image = Image.FromStream(ms, true, true);

表示:用户代码未处理ArgumentException。参数无效。任何想法为什么会这样?下面是函数的其余部分。

that says: ArgumentException was unhandled by user code. Parameter is not valid. Any ideas why this is happening? Below is the rest of the function.

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;
    }


推荐答案

Unicode不编码全部您需要表示图像的可能字节序列。

Unicode doesn't encode all possible byte sequences that you'll need to represent an image.

byte [] - > String - > byte [] 是一个转换,对于许多给定的字节序列都不起作用。你必须在整个过程中使用一个byte []。

byte[] -> String -> byte[] is a transformation that just won't work for many given sequences of bytes. You'll have to use a byte[] throughout.

例如,如果你读取字节,将它们转换为UTF-16那么字节序列就可能是丢弃为无效。以下是 UTF-16 中无效字节序列的示例。

For example, if you read the bytes, convert them to UTF-16 then it's possible that byte sequences will be discarded as invalid. Here's an example of an invalid byte sequence from UTF-16.


代码点U + D800到U + DFFF Unicode标准永久
为UTF-16编码保留这些代码点值和
跟踪代理人,他们永远不会被分配一个字符,所以
应该没有理由对它们进行编码。官方Unicode
标准表示所有UTF表单(包括UTF-16)都不能对这些代码点编码

Code points U+D800 to U+DFFF[edit] The Unicode standard permanently reserves these code point values for UTF-16 encoding of the lead and trail surrogates, and they will never be assigned a character, so there should be no reason to encode them. The official Unicode standard says that all UTF forms, including UTF-16, cannot encode these code points.

这篇关于在C#中从字符串转换为Image的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆