从流加载DDS文件并在WPF应用程序中显示?

时间:2014-05-12 20:23:13

标签: c# .net wpf .net-4.5 dds-format

我正在尝试加载DirectDraw Surface(DDS)文件并将其显示在WPF应用程序中。 这就是我从zip存档获取流的方式:

using (ZipArchive clientArchive = ZipFile.OpenRead(levelsPath + mapName + @"\client.zip"))
{
    var entry = clientArchive.GetEntry("hud/minimap/ingamemap.dds");
    var stream = entry.Open();
}

现在,如何在WPF应用程序中显示DDS图像(只是第一个,质量最高的mipmap)?

2 个答案:

答案 0 :(得分:2)

我最近使用了来自kprojects的DDSImage类。它可以加载DXT1和DXT5压缩DDS文件。

只需使用字节数组创建一个新实例,并通过images类型的属性Bitmap[]访问所有mipmap:

DDSImage img = new DDSImage(File.ReadAllBytes(@"e:\myfile.dds"));

for (int i = 0; i < img.images.Length; i++)
{
    img.images[i].Save(@"e:\mipmap-" + i + ".png", ImageFormat.Png);
} 

我将你的mipmap作为Bitmap,你可以用Image - Control来显示它。要创建一个BitmapSource,基于内存中的位图this answer指出了正确的方法。

答案 1 :(得分:0)

using (ZipArchive clientArchive = ZipFile.OpenRead(levelsPath + mapName + @"\client.zip"))
{
    var entry = clientArchive.GetEntry("hud/minimap/ingamemap.dds");
    var stream = entry.Open();
    ImageObject.Source = DDSConverter.Convert(stream,null,null,null);
}

取自here.

public class DDSConverter : IValueConverter
{
    private static readonly DDSConverter defaultInstace = new DDSConverter();

    public static DDSConverter Default
    {
        get
        {
            return DDSConverter.defaultInstace;
        }
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
        {
            throw new ArgumentNullException("value");
        }
        else if (value is Stream)
        {
            return DDSConverter.Convert((Stream)value);
        }
        else if (value is string)
        {
            return DDSConverter.Convert((string)value);
        }
        else if (value is byte[])
        {
            return DDSConverter.Convert((byte[])value);
        }
        else
        {
            throw new NotSupportedException(string.Format("{0} cannot convert from {1}.", this.GetType().FullName, value.GetType().FullName));
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException(string.Format("{0} does not support converting back.", this.GetType().FullName));
    }

    public static ImageSource Convert(string filePath)
    {
        using (var fileStream = File.OpenRead(filePath))
        {
            return DDSConverter.Convert(fileStream);
        }
    }

    public static ImageSource Convert(byte[] imageData)
    {
        using (var memoryStream = new MemoryStream(imageData))
        {
            return DDSConverter.Convert(memoryStream);
        }
    }

    public static ImageSource Convert(Stream stream)
    {
        ...
    }
}

以下是一个简单的用法示例:

<Image x:Name="ImageObject" Source="{Binding Source=Test.dds, Converter={x:Static local:DDSConverter.Default}}" />