从 ByteArray 转换为位图后 EndInit() 上的 System.NotSupportedException

问题描述 投票:0回答:0

我选择一个图像,对像素应用一些效果,然后尝试将其显示在原始图像的右侧。这是通过

MemoryStream
完成的。将包含已处理像素的字节数组转换为
BitmapImage
后,出现异常。

private void LoadImage_Click(object sender, RoutedEventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog();
    ofd.RestoreDirectory = true;

    if (ofd.ShowDialog() == true)
    {
        string FileName = ofd.FileName;
        _originalImage = new BitmapImage();
        _originalImage.BeginInit();
        _originalImage.UriSource = new Uri(FileName);
        _originalImage.EndInit();
        OriginalImage.Source = _originalImage;
    }
}

private async void ApplyFilter_Click(object sender, RoutedEventArgs e)
{
    int stride = _originalImage.PixelWidth * 4; 
    long size = Convert.ToUInt32(_originalImage.PixelWidth * stride); 
    byte[] OriginalPixels = new byte[size];
    _originalImage.CopyPixels(OriginalPixels, stride, 0);
    BitmapImage source = await ToBlackAndWhiteImage(OriginalPixels);
    ChangedImage.Source = source;
}

private Task<BitmapImage> ToBlackAndWhiteImage(byte[] originalPixels)
{ 
    for (long i = 0; i < originalPixels.Length-3; i+=3)
    {
        short red = originalPixels[i];
        short green = originalPixels[i+1];
        short blue = originalPixels[i+2];
        int average = (red + green + blue) / 3;
        originalPixels[i] = (byte)average;
        originalPixels[i+1] = (byte)average;
        originalPixels[i+2] = (byte)average;
    }

    using (MemoryStream ms = new MemoryStream(originalPixels))
    {
        BitmapImage blackAndWhiteImage = new BitmapImage();
        blackAndWhiteImage.BeginInit();
        blackAndWhiteImage.CacheOption = BitmapCacheOption.OnLoad;
        blackAndWhiteImage.StreamSource = ms;
        blackAndWhiteImage.EndInit(); //EXCEPTION HERE

        return Task.FromResult(blackAndWhiteImage);
    }
}
c# arrays bitmap memorystream
© www.soinside.com 2019 - 2024. All rights reserved.