1.前言:
某些生產設備會輸出TIFF的圖檔格式,將多張影像存放在同一個TIFF的檔案中,利用C#程式我們可以進行分割讀取每張影像檔。

2.說明:
TIFF的格式說明請參考:
http://en.wikipedia.org/wiki/Tagged_Image_File_Format

有關TIFF檔案的分割與合併可參考MSDN的說明:
http://code.msdn.microsoft.com/windowsdesktop/Split-multi-page-tiff-file-058050cc
http://msdn.microsoft.com/zh-tw/library/system.drawing.imaging.encoder.saveflag.aspx

加入命名空間:

using System.Drawing.Imaging;

程式碼

//分割TIFF圖檔
private void SplitTiffImages(string sourceFilePath, string destFilePath)
{
	Image image = Image.FromFile(sourceFilePath);
	int frames = 0;
	Guid[] guid = image.FrameDimensionsList;
	FrameDimension fd = new FrameDimension(guid[0]);            
	frames = image.GetFrameCount(fd);

	for (int i = 0; i < frames; i++)
	{
		image.SelectActiveFrame(fd, i);
		image.Save(destFilePath + @"\pic_" + i.ToString() + ".tif", System.Drawing.Imaging.ImageFormat.Tiff);
	}
}

//合併TIFF圖檔
private void MergeTiffImages(string[] sourceFilePath, string destFilePath)
{
	Bitmap multiPages = null;
	EncoderParameters eParam = new EncoderParameters(1);
	Encoder myEncoder = Encoder.SaveFlag;
	eParam.Param[0] = new EncoderParameter(myEncoder, (long)EncoderValue.MultiFrame);
	ImageCodecInfo codecInfo = null;

	foreach (ImageCodecInfo imgCodecInfo in ImageCodecInfo.GetImageEncoders())
	{
		if (imgCodecInfo.MimeType == "image/tiff")
		{
			codecInfo = imgCodecInfo;
			break;
		}
	}

	for (int i = 0; i < sourceFilePath.Length; i++)
	{
		if (i == 0)
		{
			multiPages = (Bitmap)Image.FromFile(sourceFilePath[i]);
			multiPages.Save(destFilePath, codecInfo, eParam);
		}
		else
		{
			eParam.Param[0] = new EncoderParameter(myEncoder, (long)EncoderValue.FrameDimensionPage);
			multiPages.SaveAdd((Bitmap)Image.FromFile(sourceFilePath[i]), eParam);
		}
		if (i == sourceFilePath.Length - 1)
		{
			eParam.Param[0] = new EncoderParameter(myEncoder, (long)EncoderValue.Flush);
			multiPages.SaveAdd(eParam);
		}
	}
}

3.應用:

//分割TIFF圖檔
string sourceFilePath = @"d:\tmp\tiff\test.tif";
string destFilePath = @"d:\tmp\tiff\split";
SplitTiffImages(sourceFilePath, destFilePath);

//合併TIFF圖檔
string[] sourceFilePath = { @"d:\tmp\tiff\AFM1.TIF", @"d:\tmp\tiff\AFM2.TIF", @"d:\tmp\tiff\AFM3.TIF" };
string destFilePath = @"d:\tmp\tiff\merge\merge.tif";
MergeTiffImages(sourceFilePath, destFilePath);

圖例:

tiffsplit  

arrow
arrow
    文章標籤
    C# TIFF
    全站熱搜
    創作者介紹
    創作者 西夏普 的頭像
    西夏普

    西夏普的部落格

    西夏普 發表在 痞客邦 留言(4) 人氣()