将XNA Texture2D转换为System.Windows.Media.Imaging.BitmapImage

时间:2014-04-17 07:31:19

标签: c# windows-phone-7 xna

我需要将Texture2D转换为BitmapImage,我发现了一种方法,但是在Windows Phone 7上的这个解决方案已经知道Texture2D.SaveAsJpeg方法调用中的内存泄漏问题。我尝试过:通过调用Texture2D.SaveAsJpeg将texture2d保存在isolatedstorage中,然后使用此纹理从isolatedstorage流加载并从该流创建BitmapImage

public static void SaveTextureToISF(string fileName, Texture2D texture)
        {
            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (
                    IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(fileName, FileMode.Create, file)
                    )
                {
                    texture.SaveAsPng(fileStream, texture.Width, texture.Height); //Memory leak Here
                    fileStream.Close();
                }
            }
        }

        public static BitmapImage LoadTextureFrom(string fileName)
        {
            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (
                    IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(fileName,
                                                                                         FileMode.Open,
                                                                                         FileAccess.Read, file))
                {
                    BitmapImage bmp = new BitmapImage();
                    bmp.SetSource(fileStream);
                    return bmp;
                }
            }
        }

任何其他解决方案,没有泄漏?

1 个答案:

答案 0 :(得分:0)

ImageTools诀窍。

public BitmapImage ConvertTexture2DToBitmapImage(Texture2D texture2D)
        {
            byte[] textureData = new byte[4 * texture2D.Width * texture2D.Height];
            texture2D.GetData(textureData);
            ExtendedImage extendedImage = new ExtendedImage();
            extendedImage.SetPixels(texture2D.Width, texture2D.Height, textureData);
            JpegEncoder encoder = new JpegEncoder();
            using (Stream picStream = new MemoryStream())
            {
                encoder.Encode(extendedImage, picStream);
                picStream.Position = 0;
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.SetSource(picStream);
                return bitmapImage;
            }
        }