【问题标题】:Convert XNA Texture2D to System.Windows.Media.Imaging.BitmapImage将 XNA Texture2D 转换为 System.Windows.Media.Imaging.BitmapImage
【发布时间】:2014-04-17 07:31:19
【问题描述】:

我需要将 Texture2D 转换为 BitmapImage,并且我找到了一种方法来做到这一点,但是 windows phone 7 上的这个解决方案在 Texture2D.SaveAsJpeg 方法调用中存在内存泄漏问题。我尝试过:通过调用 Texture2D.SaveAsJpeg 将 texture2d 保存在隔离存储中,然后使用此纹理从隔离存储流加载并从该流创建 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;
                }
            }
        }

任何其他解决方案,不会泄漏?

【问题讨论】:

  • 我建议的解决方案是如何在 ISF 中保存 textures2d 的解决方法。但是这个关于将texture2d转换为BitmapImage的问题。
  • 对不起,没有注意到其他解决方案不适用于WinPhone。
  • 我想这样做的方法是使用GetData 方法接收原始Texture2D 数据,然后手动转换它。为此,我已经看到很多对imagetools.codeplex.com 的引用,但找不到示例。这个适用于桌面 XNA benbarefield.com/blog/2009/03/04/bitmap-from-texture2d 但也许它可以给你任何想法..
  • Imagetools 解决了这个问题,我稍后会发布解决方案

标签: c# windows-phone-7 xna


【解决方案1】:

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

【讨论】:

  • 别忘了DisposeMemoryStream,否则你会得到另一个泄漏:)
猜你喜欢
  • 1970-01-01
  • 2012-04-04
  • 1970-01-01
  • 1970-01-01
  • 2013-01-12
  • 1970-01-01
  • 1970-01-01
  • 2018-09-04
相关资源
最近更新 更多