c# - 从 wpf 中的数组裁剪图像时出现问题

标签 c# wpf image grayscale

我有一个方法可以检索 16 位 tiff 图像: 我只保留相关信息。

我主要使用:

        Stream imageStreamSource = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
        TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
        
        BitmapSource bitmapSource = decoder.Frames[0];
        w = bitmapSource.PixelWidth; h = bitmapSource.PixelHeight;//width and height

        stride = w * bitmapSource.Format.BitsPerPixel / 8;//stride
        int byteSize = stride * h * bitmapSource.Format.BitsPerPixel / 16;//16 for a ushort array
        data = new ushort[byteSize];
        
        bitmapSource.CopyPixels(data, stride, 0); //Get pixels data into data array
        //bmpSource = bitmapSource;//used for reference
        originalFileData = new ushort[data.Length / 2];//used for reference (1 dimensional array representing the adus )
        Array.Copy(data, originalFileData, originalFileData.Length);
        bmp.WritePixels(new Int32Rect(0, 0, w, h), originalFileData, stride, 0);

我跟踪传递给 WritePixels 方法的数组并将其称为“Filedata”以进行一些图像处理

我有一个裁剪方法:

crop(Rect rect) 
    {
    int newWidth=(int)Math.Floor(rect.TopRight.X-rect.TopLeft.X);
    int newHeight=(int)Math.Floor(rect.BottomRight.Y-rect.TopRight.Y);
    ushort[] newdata=new ushort[newWidth*newHeight];
    for (int i = (int)rect.TopLeft.X, i2 = 0; i2 < newWidth; i++, i2++)
        for (int j = (int)rect.TopLeft.Y, j2 = 0; j2 < newHeight; j++, j2++)
            newdata[j2 * newWidth + i2] = Filedata[j * Width + i];

我尝试通过这种方式从数组 newdata 中制作一个新图像:

        WriteableBitmap bmp = new WriteableBitmap(newWidth, newHeight, dpi, dpi, PixelFormats.Gray16, null);
        bmp.WritePixels(new Int32Rect(0, 0, newWidth, newHeight), newdata,stride, 0);
        

但是最后一个方法给了我这个异常(exception):

"An unhandled exception of type 'System.ArgumentException' occurred in PresentationCore.dll

Additional information: Buffer size is not sufficient."

现在据我所知,我在第二部分中使用了与第一部分相同的方法,但我无法裁剪!

任何帮助将不胜感激!非常感谢!

最佳答案

我猜stride值应该与更新矩形的实际宽度相匹配:

stride = newWidth * (bmp.Format.BitsPerPixel + 7) / 8;
bmp.WritePixels(new Int32Rect(0, 0, newWidth, newHeight), newdata, stride, 0);

关于c# - 从 wpf 中的数组裁剪图像时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13727788/

相关文章:

WPF 用户控件命令绑定(bind)到窗口 View 模型

ios - swift ...当按下按钮并将其恢复正常时,如何更改图像?

html - Bootstrap 3 背景图像多个部分

c# - 一旦显示 BarcodePickerController,通过 MonoTouch 使用 RedLaser SDK 就会崩溃

c# - 如何最好地检查 cookie 是否存在?

c# - WPF TextBox 显示的值不等于 TextBox.Text

javascript - 将变量分配给 img src

c# - 如何在 C# 中传递和使用泛型对象?

c# - 依赖属性是否实现享元模式?

c# - 使用 C# 进行游戏开发