我有一个允许我检索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'类型异常
其他信息:缓冲区大小不足。“
现在据我所知,我在第二部分使用与第一部分相同的方法,但我无法裁剪!
任何帮助都将非常感谢!非常感谢!
答案 0 :(得分:3)
我想stride
值应该与更新矩形的实际宽度相匹配:
stride = newWidth * (bmp.Format.BitsPerPixel + 7) / 8;
bmp.WritePixels(new Int32Rect(0, 0, newWidth, newHeight), newdata, stride, 0);