2

我有一种方法可以让我检索 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);
        

但是最后一种方法给了我这个例外:

“PresentationCore.dll 中出现‘System.ArgumentException’类型的未处理异常

附加信息:缓冲区大小不足。”

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

非常感激任何的帮助!多谢!

4

1 回答 1

3

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

stride = newWidth * (bmp.Format.BitsPerPixel + 7) / 8;
bmp.WritePixels(new Int32Rect(0, 0, newWidth, newHeight), newdata, stride, 0);
于 2012-12-05T16:52:25.050 回答