public void Example() { if (!File.Exists(fileName)) { Console.WriteLine("File not found. Aborting."); return; } // Load the multipaged bitmap. // 'OpenMultiBitmapEx' tries to find the correct file format, loads the bitmap // with default options, with write support and does not use caching. dib = FreeImage.OpenMultiBitmapEx(fileName); // Check whether loading succeeded. if (dib.IsNull) { Console.WriteLine("File could not be loaded. Aborting."); return; } // Get the number of bitmaps the multipaged bitmap contains. int count = FreeImage.GetPageCount(dib); // Multipaged bitmaps consist of multiple single FIBITMAPs FIBITMAP page = new FIBITMAP(); // There are bitmaps we can work with. if (count > 0) { // Lock a random bitmap to work with. page = FreeImage.LockPage(dib, rand.Next(0, count)); } // Check whether locking succeeded. if (page.IsNull) { // Locking failed. Unload the bitmap and return. FreeImage.CloseMultiBitmapEx(ref dib); return; } // Get a list of locked pages. This can be usefull to check whether a page has already been locked. int[] lockedPages = FreeImage.GetLockedPages(dib); // Lets modify the page. if (FreeImage.AdjustGamma(page, 2d)) { Console.WriteLine("Successfully changed gamma of page {0}.", lockedPages[0]); } else { Console.WriteLine("Failed to adjust gamma ..."); } // Print out the list of locked pages foreach (int i in lockedPages) { Console.WriteLine("Page {0} is locked.", i); } // Use 'UnlockPage' instead of 'Unload' to free the page. Set the third parameter to 'true' // so that FreeImage can store the changed page within the multipaged bitmap. FreeImage.UnlockPage(dib, page, true); // Retieve the list again to see whether unlocking succeeded. lockedPages = FreeImage.GetLockedPages(dib); // No output should be produced here. foreach (int i in lockedPages) { Console.WriteLine("Page {0} is still locked.", i); } // If there are more than one page we can swap them if (count > 1) { if (!FreeImage.MovePage(dib, 1, 0)) { Console.WriteLine("Swapping pages failed."); } } if (count > 2) { // Lock page 2 page = FreeImage.LockPage(dib, 2); if (!page.IsNull) { // Clone the page for later appending FIBITMAP temp = FreeImage.Clone(page); // Unlock the page again FreeImage.UnlockPage(dib, page, false); // Delete the page form the multipaged bitmap FreeImage.DeletePage(dib, 2); // Append the clone again FreeImage.AppendPage(dib, temp); // Check whether the number of pages is still the same Console.WriteLine("Pages before: {0}. Pages after: {1}", count, FreeImage.GetPageCount(dib)); // Unload clone to prevent memory leak FreeImage.UnloadEx(ref temp); } } // We are done and close the multipaged bitmap. if (!FreeImage.CloseMultiBitmapEx(ref dib)) { Console.WriteLine("Closing bitmap failed!"); } }
//private void ergDir(string path, ref List<string> lstPath) { // if(!Directory.Exists(path)) { // return; // } // DirectoryInfo info = new DirectoryInfo(path); // foreach(FileInfo NextFile in info.GetFiles()) { // if(NextFile.Name == "0-0-11.grid") // continue; // // 获取文件完整路径 // string heatmappath = NextFile.FullName; // } //} public string convert(string[] srcMultiPath, string dstDir, string multiSizeBpp, string outType = "auto", string operate = "rename", bool mergeOutput = false) { string rstInfo = "Success"; //HashSet<int> hsIconSize = new HashSet<int>(); //for(int i = 0; i < lstSupportIconSize.Length; ++i) { // hsIconSize.Add(lstSupportIconSize[i]); //} //HashSet<int> hsBpp = new HashSet<int>(); //for(int i = 0; i < lstSupportBpp.Length; ++i) { // hsBpp.Add(lstSupportBpp[i]); //} List <int> lstIcoSize = new List <int>(); List <int> lstIcoBpp = new List <int>(); // check param : outType if (!hsSupportOutType.Contains(outType)) { return(getErrorInfo(outType)); } // check param : operate if (!hsSupportOperate.Contains(operate)) { return(getErrorInfo(operate)); } // format param : size & bpp; string[] arr = multiSizeBpp.Split(new string[] { ";", ";" }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < arr.Length; ++i) { string[] arr2 = arr[i].Split(new string[] { ",", "," }, StringSplitOptions.RemoveEmptyEntries); if (arr2.Length <= 0) { continue; } int size; int bpp = 32; bool isOk = int.TryParse(arr2[0], out size); if (!isOk || !hsIconSize.Contains(size)) { return(getErrorInfo(multiSizeBpp)); } if (arr2.Length >= 2) { isOk = int.TryParse(arr2[1], out bpp); if (!isOk) { return(getErrorInfo(multiSizeBpp)); } } if (!hsBpp.Contains(bpp)) { return(getErrorInfo(multiSizeBpp)); } lstIcoSize.Add(size); lstIcoBpp.Add(bpp); } if (lstIcoSize.Count == 0) { lstIcoSize.Add(48); lstIcoBpp.Add(32); } //List<string> lstSrcPath = new List<string>(); //for(int i = 0; i < srcMultiPath.Length; ++i) { // if(Directory.Exists(path)) { // continue; // } //} for (int j = 0; j < srcMultiPath.Length; ++j) { List <DibMd> lstData = new List <DibMd>(); string path = srcMultiPath[j]; if (!File.Exists(path) && !Directory.Exists(path)) { continue; } string suffix = Path.GetExtension(path).ToLower(); string dir = Path.GetDirectoryName(path) + "/"; if (dstDir != "") { dir = dstDir + "/"; Directory.CreateDirectory(dir); } string outSuffix = getOutFileSuffix(suffix, outType); // 只有输出格式ico的才能合并输出 bool realMergeOutput = mergeOutput; if (outSuffix != ".ico") { realMergeOutput = false; } string mergeDstPath = dir + Path.GetFileNameWithoutExtension(path) + outSuffix; if (realMergeOutput) { if (File.Exists(mergeDstPath)) { switch (operate) { case "jump": continue; case "overwrite": break; case "cancel": return("Cancel"); case "rename": default: mergeDstPath = renameDstFileName(mergeDstPath); break; } } } for (int i = 0; i < lstIcoSize.Count; ++i) { //if(Directory.Exists(path)) { // continue; //} string fname = Path.GetFileNameWithoutExtension(path); if (!realMergeOutput && !isDefaultIcon(lstIcoSize[i], lstIcoBpp[i])) { fname = $"{fname}_{lstIcoSize[i]}_{lstIcoBpp[i]}"; } string dstPath = dir + fname + outSuffix; if (File.Exists(dstPath)) { switch (operate) { case "jump": continue; case "overwrite": break; case "cancel": return("Cancel"); case "rename": default: dstPath = renameDstFileName(dstPath); break; } } //convert(path, dstPath, lstIcoSize[i], lstIcoBpp[i]); try { DibMd md = loadFile(path, lstIcoSize[i]); DibMd outMd = formatOutput(md, lstIcoSize[i], lstIcoBpp[i]); md?.Dispose(); if (outMd == null) { continue; } if (realMergeOutput) { lstData.Add(outMd); } else { save(outMd, dstPath); } } catch (Exception) { } } // 合并输出 if (realMergeOutput && lstData.Count > 0) { try { FIMULTIBITMAP fmb = FreeImage.OpenMultiBitmap(FREE_IMAGE_FORMAT.FIF_ICO, mergeDstPath, true, false, false, FREE_IMAGE_LOAD_FLAGS.ICO_MAKEALPHA); for (var i = 0; i < lstData.Count; ++i) { FreeImage.AppendPage(fmb, lstData[i].dib); lstData[i].Dispose(); } lstData.Clear(); FreeImage.CloseMultiBitmapEx(ref fmb, FREE_IMAGE_SAVE_FLAGS.BMP_SAVE_RLE); } catch (Exception) { } } } return(rstInfo); }
// Сохраняет выделенные файлы в TIFF private void btnTIFF_Click(object sender, EventArgs e) { if (0 == listView1.SelectedItems.Count) { return; } bool deleteFiles = chkDeleteFiles.Checked; // Удалять jpeg'и после создания tiff savePDFDialog.Filter = "Файлы TIFF|*.tif;*.tiff"; savePDFDialog.InitialDirectory = PDFInitialDir; if (DialogResult.OK != savePDFDialog.ShowDialog()) { return; } Cursor.Current = Cursors.WaitCursor; // Вариант с FreeImage - быстро, но сложнее и иногда инвертирует цвета // Сохранить первую страницу FIBITMAP dib_color = FreeImage.LoadEx(scanFileNames[listView1.SelectedItems[0].Index]); FIBITMAP dib = FreeImage.ConvertToGreyscale(dib_color); FreeImage.UnloadEx(ref dib_color); if (FREE_IMAGE_COLOR_TYPE.FIC_MINISBLACK == FreeImage.GetColorType(dib)) { FreeImage.Invert(dib); } deleteFiles = FreeImage.SaveEx(ref dib, savePDFDialog.FileName, FREE_IMAGE_FORMAT.FIF_TIFF, FREE_IMAGE_SAVE_FLAGS.TIFF_CCITTFAX4, FREE_IMAGE_COLOR_DEPTH.FICD_01_BPP, true); FreeImage.UnloadEx(ref dib); if (listView1.SelectedItems.Count > 1) { string tmpFile = Path.GetTempFileName() + ".tif"; FIBITMAP fib; FIBITMAP fib_color; FIMULTIBITMAP fmb = FreeImage.OpenMultiBitmapEx(savePDFDialog.FileName); // Добавить остальные страницы for (int i = 1; i < listView1.SelectedItems.Count; i++) { fib_color = FreeImage.LoadEx(scanFileNames[listView1.SelectedItems[i].Index]); fib = FreeImage.ConvertToGreyscale(fib_color); FreeImage.UnloadEx(ref fib_color); if (FREE_IMAGE_COLOR_TYPE.FIC_MINISBLACK == FreeImage.GetColorType(fib)) { FreeImage.Invert(fib); } FreeImage.SaveEx(ref fib, tmpFile, FREE_IMAGE_FORMAT.FIF_TIFF, FREE_IMAGE_SAVE_FLAGS.TIFF_CCITTFAX4, FREE_IMAGE_COLOR_DEPTH.FICD_01_BPP, true); fib = FreeImageAPI.FreeImage.LoadEx(tmpFile); FreeImage.AppendPage(fmb, fib); FreeImage.UnloadEx(ref fib); File.Delete(tmpFile); } deleteFiles = FreeImage.CloseMultiBitmapEx(ref fmb); } /* * // Вариант с ImageMagick - проще, но очень медленно * int s = 0; * * MagickImageCollection images = new MagickImageCollection(); * foreach (ListViewItem item in listView1.SelectedItems) * { * images.Add(scanFileNames[item.Index]); * images[s].Strip(); // По аналогии с PDF на всякий случай * images[s].Format = MagickFormat.Tif; * images[s].Settings.Compression = CompressionMethod.Group4; * images[s].Depth = 1; * s++; * } * try * { * images.Write(savePDFDialog.FileName, MagickFormat.Tif); * } * catch (MagickException me) * { * toolStripStatus.Text = me.Message; * deleteFiles = false; * } * images.Dispose(); */ if (deleteFiles) { btnDelete_Click(btnPDF, null); } Cursor.Current = Cursors.Default; }