MemoryStream抛出System.ObjectDisposedException

时间:2018-11-27 10:01:07

标签: wpf memorystream 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时,我得到了异常。

预先感谢

1 个答案:

答案 0 :(得分:2)

在设置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();
}