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);
圖例:
文章標籤
全站熱搜

請教一下 使用此方法合併大量圖片時 記憶體使用會一直上升降不下來 到最後會發生GDI+ 泛型錯誤 請問有方法避免嗎 謝謝
您好,参考如下修改,我試著合并600個檔案,記憶體沒上升,也無出現錯誤,先試下。 else{ eParam.Param[0]=new EncoderParameter(myEncoder,(long)Encoder Value.FrameDimensionPage); Bitmap a = (Bitmap)Image.FromFile(sourceFilePath[i],eParam); multiPages.SaveAdd(a,eParam); a.Dispose(); } 西夏普
太感謝 可以了 只是 Bitmap a = (Bitmap)Image.FromFile(sourceFilePath[i],eParam); 是不是應該改 Bitmap a = (Bitmap)Image.FromFile(sourceFilePath[i]); 就好??
另外又發現了一個問題 我合併完的JPG檔想要刪掉 可是卻出現圖檔被另一處理序使用的錯誤 但我能dispose的 都dispose了啊@@ 該如何解決呢? 謝謝
沒事了 下GC.Collect(); 就沒被咬住了@@ 真神奇