I have a method that allows me to retrieve a 16 bit tiff image:
I am keeping only relevant information.
I use mainly:
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);
I keep track of the array that I pass into the WritePixels method and call it "Filedata" to do a bit of image processing
I have a crop method:
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];
and I try to make a new image out of the array newdata this way:
WriteableBitmap bmp = new WriteableBitmap(newWidth, newHeight, dpi, dpi, PixelFormats.Gray16, null);
bmp.WritePixels(new Int32Rect(0, 0, newWidth, newHeight), newdata,stride, 0);
but this last method gives me this exception:
"An unhandled exception of type ‘System.ArgumentException’ occurred in PresentationCore.dll
Additional information: Buffer size is not sufficient."
Now as far as I can see, I use the same method in the second part as in the first part, yet I can’t crop!
Any help would be most appreciated! thanks a lot!
I guess the
stridevalue should match the actual width of the update rectangle: