// Instantiate the dialog box var dlg = new Microsoft.Win32.OpenFileDialog { FileName = "", Filter = "All Files|*.*|PNG Files|*.png|JPG Files|*.jpg|TIF Files|*.tif" }; var result = dlg.ShowDialog(); // Process open file dialog box results if (result == true) { // Open a Stream and decode a TIFF image. Stream imageStreamSource = new FileStream(dlg.FileName, FileMode.Open, FileAccess.Read, FileShare.Read); var decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); BitmapSource bitmapSource = decoder.Frames[0]; Int32 PixelHeight = bitmapSource.PixelHeight; // 图像高度 Int32 PixelWidth = bitmapSource.PixelWidth; // 图像宽度 Int32 Stride = (PixelWidth * bitmapSource.Format.BitsPerPixel + 7) / 8; // 跨距宽度 if(bitmapSource.Format.BitsPerPixel ==8) { Byte[] gray8 = new Byte[PixelHeight * PixelWidth];//8bit 位深 bitmapSource.CopyPixels(gray8, Stride, 0); } else if (bitmapSource.Format.BitsPerPixel == 16) { ushort[] gray16 = new ushort[PixelHeight * PixelWidth];//16bit 位深 bitmapSource.CopyPixels(gray16, Stride, 0); } }
效果如下:
unsafe { int lenth = width * height;//相机buff照片的宽度和高度 UInt16* bufi = (UInt16*)buf.ToPointer();//从相机buff中读取16bit灰度数据 UInt16[] data = new UInt16[lenth]; byte[] bufBytes = new byte[lenth*2]; for (int i = 0; i < lenth; i++) { data[i] = bufi[i]; } IntPtr intptr = Marshal.UnsafeAddrOfPinnedArrayElement(data, 0); Marshal.Copy(intptr,bufBytes,0,lenth*2);//将16bit数据转化成两个8bit数据 BitmapPalette myPalette = BitmapPalettes.Gray16; int rawStride = (width * 16 + 7) / 8;//16bit 位深 BitmapSource image = BitmapSource.Create(width, height, 96, 96, PixelFormats.Gray16, myPalette, bufBytes, rawStride); FileStream f = new FileStream(name, FileMode.Create); TiffBitmapEncoder encoder = new TiffBitmapEncoder();//tif编码格式 encoder.Compression = TiffCompressOption.Zip; encoder.Frames.Add(BitmapFrame.Create(image)); encoder.Save(f); f.Close(); }