1. 程式人生 > 其它 >C# 讀寫16位tif圖片灰度資料

C# 讀寫16位tif圖片灰度資料

            // 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); } }
讀16位tif圖片灰度資料

效果如下:

            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();
            }
從相機buff中將16bit灰度資料寫入tif照片

參考連結https://docs.microsoft.com/zh-cn/dotnet/desktop/wpf/graphics-multimedia/how-to-encode-and-decode-a-tiff-image?view=netframeworkdesktop-4.8