功能:
合並多個圖片為一個TIFF文件
效果圖:
第二頁
第三頁
功能函數實現:
public bool SaveMultipage(Image[] bmp, string location, string type) { if (bmp != null) { try { File.Delete(location); var codecInfo = getCodecForstring(type); if (bmp.Length == 1) { var iparams = new EncoderParameters(1); var iparam = Encoder.Compression; var iparamPara = new EncoderParameter(iparam, (long)(EncoderValue.CompressionNone)); iparams.Param[0] = iparamPara; bmp[0].Save(location, codecInfo, iparams); } else if (bmp.Length > 1) { // Save the first page (frame). // URL:http://www.bianceng.cn/Programming/csharp/201410/45752.htm var encoderParam1 = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.MultiFrame); var encoderParam2 = new EncoderParameter(Encoder.Compression, (long) EncoderValue.CompressionNone); var encoderParams = new EncoderParameters(2); encoderParams.Param[0] = encoderParam1; encoderParams.Param[1] = encoderParam2; bmp[0].Save(location, codecInfo, encoderParams); for (int i = 1; i < bmp.Length; i++) { if (bmp[i] == null) break; encoderParams.Param[0] = encoderParam1; encoderParams.Param[1] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.FrameDimensionPage); bmp[0].SaveAdd(bmp[i], encoderParams); } encoderParams.Param[0] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.Flush); bmp[0].SaveAdd(encoderParams); } return true; } catch (Exception ee) { throw new Exception(ee.Message + " Error in saving as multipage "); } } return false; } private ImageCodecInfo getCodecForstring(string type) { var info = ImageCodecInfo.GetImageEncoders(); return (info.Select(t => new {t, enumName = type}) .Where(@t1 => @t1.t.FormatDescription.Equals(@t1.enumName)) .Select(@t1 => @t1.t)) .FirstOrDefault(); }
代碼說明:參數:圖片數組,保存文件的位置,保存類型
單元測試代碼實現:
01.[TestMethod]
02. public void Multiple_Image_Into_1Tiff_With_MultiplePages()
03. {
04. const string multipleImgPath = "C:\\Users\\Public\\Pictures\\Sample Pictures";
05. var files = new DirectoryInfo(multipleImgPath).GetFiles("*.jpg", SearchOption.TopDirectoryOnly);
06. Assert.IsTrue(files.Length > 1);
07. var imgs = files.Select(f => Image.FromFile(f.FullName));
08. SaveMultipage(imgs.ToArray(), "C:\\multiplePageTiff.tiff", "TIFF");
09.
10. const string singleImgPath = @"C:\Users\{your_pc_name}\Pictures\SingleImg";
11. files = new DirectoryInfo(singleImgPath).GetFiles("*.jpg", SearchOption.TopDirectoryOnly);
12. Assert.IsTrue(files.Length == 1);
13.
14. imgs = files.Select(f => Image.FromFile(f.FullName));
15. SaveMultipage(imgs.ToArray(), "C:\\multiplePageTiff_Single.tiff", "TIFF");
16. }
代碼說明:
1.測試多個圖片的轉化
2.測試單個突破的轉化