内存流抛出 System.ObjectDisposedException

MemoryStream throws System.ObjectDisposedException

我想为 iOS 调整图像大小,这样我就不必一直手动操作了。这应该使用 WPF 来完成,但它会抛出 ObjectDisposedException。

它的作用是用户选择一个 csproj 文件,然后选择一个将调整为 3 种尺寸的图像。调整大小后,文件应该安全地保存到磁盘,但会引发异常。

正在检索原始 BitmapImage 的字节

byte[] data = original.GetByteArray();

使用方法:

 public static byte[] GetByteArray(this BitmapImage bmi)
    {
        byte[] data;
        PngBitmapEncoder encoder = new PngBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(bmi));
        using (Sys.MemoryStream ms = new Sys.MemoryStream())
        {
            encoder.Save(ms);
            data = ms.ToArray();
        }
        return data;
    }

调整大小:

private BitmapImage ResizeImage(byte[] imageData, double dheight, double dwidth)
        {
            int height = (int)dheight;
            int width = (int)dwidth;
            BitmapImage resizedImage = new BitmapImage();

            using (Sys.MemoryStream ms = new Sys.MemoryStream(imageData))
            {
                resizedImage.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
                resizedImage.CacheOption = BitmapCacheOption.OnLoad;
                resizedImage.DecodePixelHeight = height;
                resizedImage.DecodePixelWidth = width;
                resizedImage.BeginInit();  // Needed only so we can call EndInit()
                resizedImage.StreamSource = ms;
                resizedImage.EndInit();// This does the actual loading and resizing
            }
            return resizedImage;
        }

然后保存文件:

public static void Save(this BitmapImage image, string filePath)
        {
            //PngBitmapEncoder encoder = new PngBitmapEncoder();
            //encoder.Frames.Add(BitmapFrame.Create(image));

            //using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
            //{
            //    encoder.Save(fileStream);
            //}
            File.WriteAllBytes(filePath, image.GetByteArray());
        }

我是如何使用它的:

            var bmi512 = ResizeImage(data, 512, 512);
            var bmi256 = ResizeImage(data, 256, 256);
            var bmi128 = ResizeImage(data, 128, 128);
            bmi512.Save(Sys.Path.Combine(imageFolderPath, String.Format("{0}512{1}", imageName, imageExt)));
            bmi256.Save(Sys.Path.Combine(imageFolderPath, String.Format("{0}256{1}", imageName, imageExt)));
            bmi128.Save(Sys.Path.Combine(imageFolderPath, String.Format("{0}128{1}", imageName, imageExt)));

它适用于检索原始字节[],但是当它尝试用于 bmi512 时,我得到了异常。

提前致谢

在设置 BitmapImage 的任何属性之前必须调用 BeginInit

using (var ms = new MemoryStream(imageData))
{
    resizedImage.BeginInit();
    resizedImage.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
    resizedImage.CacheOption = BitmapCacheOption.OnLoad;
    resizedImage.DecodePixelHeight = height;
    resizedImage.DecodePixelWidth = width;
    resizedImage.StreamSource = ms;
    resizedImage.EndInit();
}