在WP7上将位图保存为PNG

11

我正在尝试将位图保存为PNG文件到我的隔离存储中。我在Codeplex上找到了一个名为ImageTools的库,人们一直在推荐使用它,但是当我尝试打开该文件时,它显示为损坏。有人知道我做错了什么吗?

private static void SaveImageToIsolatedStorageAsPng(BitmapImage bitmap, string fileName)
{
    //convert to memory stream
    MemoryStream memoryStream = new MemoryStream();
    WriteableBitmap writableBitmap = new WriteableBitmap(bitmap);
    writableBitmap.SaveJpeg(memoryStream, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100);

    //encode memory stream as PNG
    ExtendedImage image = new ExtendedImage();
    image.SetSource(memoryStream);

    PngEncoder encoder = new PngEncoder();

    //Save to IsolatedStorage
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    using (var writeStream = new IsolatedStorageFileStream(fileName, FileMode.Create, store))
    {
        encoder.Encode(image, writeStream);
    }
}

你为什么要首先将其转换为较慢的格式?如果图像是JPEG格式,将其转换为PNG格式并没有任何好处。而且,查看PNG格式比JPEG格式更慢。 - Claus Jørgensen
2
需要将格式 i 转换为 PNG。 - Ryan Burnham
也许他需要透明度或无损压缩? - Andrei Rînea
1个回答

16
你正在尝试将JPEG内存流转换为PNG格式。这会使其损坏-你应该直接将位图保存为PNG格式。
我没有使用 imagetools库 尝试过这个特定的任务,但如果你 看看John Papa的博客, 看起来你需要在提供的ImageTools中调用ToImage扩展方法来处理你的WriteableBitmap。然后,你可以使用编码器将此图像写入到你打开的流中。
var img = bitmap.ToImage();
var encoder = new PngEncoder();
using (var stream = new IsolatedStorageFileStream(fileName, FileMode.Create, store))
{
    encoder.Encode(img, stream);
    stream.Close();
}

2
我明白了,我不确定还有什么其他方法可以将位图转换为流。您能否将ExtendedImage的源设置为IsolatedFileStream? - Ryan Burnham
啊 - 快速搜索后,似乎文档不是很完善 - 我已经更新了答案。 - Paul Annetts
如果使用指令"using",就不需要用"stream.close()"显式地关闭流,因为该指令会自动关闭并释放它。 - Cabuxa.Mapache

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接