。using namespace System;
using namespace System::IO;
using namespace System::Windows::Media::Imaging;
using namespace System::Windows::Media;
using namespace System::Windows::Forms;
using namespace System::Collections;
using namespace System::Collections::Generic;
using namespace System::Drawing;
using namespace System::Drawing::Imaging;
[STAThreadAttribute]
int main(int argc, char * argv[])
{
	OpenFileDialog^ dlg = gcnew OpenFileDialog();
	dlg->Filter = "tif file(*.tif)|*.tif|All files(*.*)|*.*";

	if (dlg->ShowDialog() == System::Windows::Forms::DialogResult::OK)
	{
		// Open a Stream and decode a TIFF image
		Stream^ imageStreamSource = gcnew FileStream(dlg->FileName, FileMode::Open, FileAccess::Read, FileShare::Read);
		TiffBitmapDecoder^ decoder = gcnew TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions::PreservePixelFormat, BitmapCacheOption::Default);
		
		//讀入tiff值
		BitmapSource^ bitmapSource = decoder->Frames[0];

		//初始化
		Bitmap^ myDemoMap = gcnew Bitmap(bitmapSource->PixelWidth, bitmapSource->PixelHeight, System::Drawing::Imaging::PixelFormat::Format16bppGrayScale);
		BitmapData^ data = myDemoMap->LockBits(System::Drawing::Rectangle(0, 0, bitmapSource->PixelWidth, bitmapSource->PixelHeight), System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format16bppGrayScale);		
		int bytes = data->Stride * data->Height;
		array<unsigned char>^byteArray = gcnew array<Byte>(bytes);		

		//把tiff存到bitmapData中
		bitmapSource->CopyPixels(System::Windows::Int32Rect::Empty, data->Scan0, data->Height * data->Stride, data->Stride);
		myDemoMap->UnlockBits(data);

		//把bitmapData轉存byteArray
		System::Runtime::InteropServices::Marshal::Copy(data->Scan0, byteArray, 0, bytes);
		//byteArray轉成bit		
		BitArray^ bitArray = gcnew BitArray(byteArray);	
		for (int i = 0; i < bitArray->Length; i+=16)
		{
			for (int j = 0; j < 12; j++)
				bitArray[i] = bitArray[i + j + 4];
			for (int j = 12; j < 16; j++)
				bitArray[i] = false;
		}

		//bit轉回byteArray
		bitArray->CopyTo(byteArray, 0);
		//byteArray轉回bitmapData中
		System::Runtime::InteropServices::Marshal::Copy(byteArray, 0, data->Scan0, bytes);		

		myDemoMap->LockBits(System::Drawing::Rectangle(0, 0, bitmapSource->PixelWidth, bitmapSource->PixelHeight), System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format16bppGrayScale,data );
		myDemoMap->UnlockBits(data);

		//更改檔名
		String^ delimStr = gcnew String(".");
		array<Char>^ delimiter = delimStr->ToCharArray();
		array<String^>^ words = dlg->FileName->Split(delimiter);

		//存檔
		FileStream^ stream = gcnew FileStream(words[0] + "(2)." + words[1], FileMode::Create);
		myDemoMap->Save(words[0] + "(2)." + words[1]);
	}
}

