如何将流数据转换为对象?

时间:2015-10-08 13:32:24

标签: c# dll methods stream

我有一个存储图像资源,字体资源等的dll ......

我在程序集中有一个类,它有一个返回方法,我希望能够从dll中提取资源并将它们作为一个abject返回,然后我可以转换为它们各自的类型。

这是我到目前为止的代码。

        public class GetResource
    {
            public static T LoadDllResource<T>(string ResourceFolder, string resourceName, string Extension, int width = 10, int height = 10)
            {
                Assembly myAssembly = Assembly.GetExecutingAssembly();
                Stream myStream = myAssembly.GetManifestResourceStream(myAssembly.GetName().Name + "." + ResourceFolder + "." + resourceName + "." + Extension);

// convert stream to object by doing something like this (I'm not sure)
//return (T)Convert.ChangeType(EndResultOFStreamConversion, typeof(object));
            }
    }

并以这种方式使用

    Font SomeFont1=  GetResource.LoadDllResource<Font>("Resources","Splash","ttf")

UnityEngine.Texture2D SomeImage2=  GetResource.LoadDllResource<UnityEngine.Texture2D>("Resources","SnowImage","png")

如果问题存在问题,请告诉我。谢谢你的帮助!

我在Unity Engine中工作,它不能很好地支持使用System.Drawing

的混合程序集

1 个答案:

答案 0 :(得分:0)

您可以使用System.Drawing命名空间中的Image.FromStream Method将流转换为图像(请务必先将System.Drawing.dll的引用添加到程序集中)。我不太确定'font resources'是什么意思,但我会这样做:

public class GetResource
{
    public Image GetImageFromResource(string resourceFolder, string resourceName, string extension)
    {
        return Image.FromStream(this.GetStreamFromResource(resourceFolder, resourceName, extension), true);
    }

    private Stream GetStreamFromResource(string ResourceFolder, string resourceName, string Extension)
    {
        Assembly myAssembly = Assembly.GetExecutingAssembly();
        return myAssembly.GetManifestResourceStream(myAssembly.GetName().Name + "." + ResourceFolder + "." + resourceName + "." + Extension);

    }
}