public void Test_Collection_Read()
    {
      using (MagickImageCollection collection = new MagickImageCollection())
      {
        MagickReadSettings settings = new MagickReadSettings();
        settings.Density = new Density(150);

        collection.Read(Files.RoseSparkleGIF, settings);

        Assert.AreEqual(150, collection[0].Density.X);

        settings = new MagickReadSettings();
        settings.FrameIndex = 1;

        collection.Read(Files.RoseSparkleGIF, settings);

        Assert.AreEqual(1, collection.Count);

        settings = new MagickReadSettings();
        settings.FrameIndex = 1;
        settings.FrameCount = 2;

        collection.Read(Files.RoseSparkleGIF, settings);

        Assert.AreEqual(2, collection.Count);

        settings = null;
        collection.Read(Files.RoseSparkleGIF, settings);
      }
    }
Esempio n. 2
0
 protected virtual int Pdf2imgProc(MagickImageCollection images, String pdf, int idx, int file_c)
 {
     images.Read(pdf, settings);
     int pages = images.Count;
     if (pages > this.MaxPage)
     {
         this.Result.Code = 413;
         L.D("executing pdf2img by file({0}),destination format({1}) fail with too large code({2}),count({3})",
             this.AsSrc, this.AsDstF, this.Result.Code, this.Result.Count);
         return 0;
     }
     if (idx < 0)
     {
         this.Total = new int[pages];
         this.Done = new int[pages];
         Util.set(this.Total, 1);
         Util.set(this.Done, 0);
     }
     else
     {
         this.Total[idx] = pages;
     }
     for (var i = 0; i < pages; i++)
     {
         this.Pdf2imgProc(images[i], idx, i, file_c);
     }
     return pages;
 }
Esempio n. 3
0
    public static void ConvertPDFTOneImage()
    {
      MagickReadSettings settings = new MagickReadSettings();
      // Settings the density to 300 dpi will create an image with a better quality
      settings.Density = new PointD(300, 300);

      using (MagickImageCollection images = new MagickImageCollection())
      {
        // Add all the pages of the pdf file to the collection
        images.Read(SampleFiles.SnakewarePdf, settings);

        // Create new image that appends all the pages horizontally
        using (MagickImage horizontal = images.AppendHorizontally())
        {
          // Save result as a png
          horizontal.Write(SampleFiles.OutputDirectory + "Snakeware.horizontal.png");
        }

        // Create new image that appends all the pages horizontally
        using (MagickImage vertical = images.AppendVertically())
        {
          // Save result as a png
          vertical.Write(SampleFiles.OutputDirectory + "Snakeware.vertical.png");
        }
      }
    }
    private static void WriteAndCheckProfile(MagickImageCollection images, PsdWriteDefines defines, int expectedLength)
    {
      using (MemoryStream memStream = new MemoryStream())
      {
        images.Write(memStream, defines);

        memStream.Position = 0;
        images.Read(memStream);
        CheckProfile(images[1], expectedLength);
      }
    }
    public void Test_Collection_Exceptions()
    {
      using (MagickImageCollection collection = new MagickImageCollection())
      {
        MagickReadSettings settings = new MagickReadSettings();
        settings.PixelStorage = new PixelStorageSettings();

        ExceptionAssert.Throws<ArgumentException>(delegate ()
        {
          collection.Read(Files.RoseSparkleGIF, settings);
        });
      }
    }
        public void Convert2Jpeg(bool rotate = false)
        {
            try
            {
                MagickReadSettings settings = new MagickReadSettings();

                // Settings the density to 300 dpi will create an image with a better quality
                settings.Density = new PointD(300, 300);

                using (MagickImageCollection images = new MagickImageCollection())
                {
                    // Add all the pages of the pdf file to the collection
                    images.Read(_pdf.FullName, settings);

                    if (images.Count > 0 && images[0].Format == MagickFormat.Pdf)
                    {
                        _logger.InfoFormat("Handle {0}", _pdf.FullName);

                        int page = 1;
                        foreach (MagickImage image in images)
                        {
                            var newFileName = GetFilePageName(page) + ".jpg";

                            // Need page rotation?
                            if (rotate)
                                image.Rotate(90.0);

                            // Write page to file that contains the page number
                            image.Format = MagickFormat.Jpg;
                            image.CompressionMethod = CompressionMethod.JPEG;
                            image.Quality = 75;
                            image.Write(newFileName);

                            _logger.InfoFormat("-> {0}", newFileName);

                            // Writing to a specific format works the same as for a single image
                            page++;
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message, ex);
            }
        }
 public int SplitIco(string icoFileName)
 {
     var fullName = Path.GetFullPath(icoFileName);
     var folder = Path.GetDirectoryName(fullName);
     var baseName = Path.GetFileNameWithoutExtension(fullName);
     using (var imageCollection = new MagickImageCollection())
     {
         imageCollection.Read(icoFileName);
         foreach (var image in imageCollection)
         {                    
             var pngFileName = baseName + "-" + image.Height + ".png";
             var pngFile = Path.Combine(folder, pngFileName);
             image.Write(pngFile);
         }
     }
     return 0;
 }
Esempio n. 8
0
		private static void ConvertPdfToOneTif()
		{
			// Log all events
			//MagickNET.SetLogEvents(LogEvents.All | LogEvents.Trace);
			// Set the log handler (all threads use the same handler)
			//MagickNET.Log += DetailedDebugInformationSamples.MagickNET_Log;

			string sampleDocsDirectory = @"E:\projects\ImageProcessing\sampledocs\";
			string sampleFile = "sample6.pdf";

			try
			{
				MagickReadSettings settings = new MagickReadSettings();
				settings.Density = new PointD(300, 300);

				using (MagickImageCollection images = new MagickImageCollection())
				{
					// Add all the pages of the source file to the collection
					images.Read(Path.Combine(sampleDocsDirectory, sampleFile), settings);

					//Show page count
					Console.WriteLine("page count for {0} {1}", sampleFile, images.Count);

					string baseFileName = Path.GetFileNameWithoutExtension(sampleFile);

					// Create new image that appends all the pages horizontally
					//using (MagickImage vertical = images.AppendVertically())
					//{
					//	vertical.CompressionMethod = CompressionMethod.Group4;
					//	Console.WriteLine("saving file: {0}", baseFileName + ".tif");
					//	vertical.Write(sampleDocsDirectory + baseFileName + ".tif");
					//}

					Console.WriteLine("saving file: {0}", baseFileName + ".tif");
					images.Write(sampleDocsDirectory + baseFileName + ".tif");
				}

			}
			catch (Exception ex)
			{
				Console.WriteLine("ConvertPdfToOneTif {0}", ex.Message);
			}
		}
    public void Test_AdditionalInfo()
    {

      using (MagickImageCollection images = new MagickImageCollection())
      {
        images.Read(Files.Coders.LayerStylesSamplePSD);

        CheckProfile(images[1], 264);

        var defines = new PsdWriteDefines()
        {
          AdditionalInfo = PsdAdditionalInfo.All
        };
        WriteAndCheckProfile(images, defines, 264);

        defines.AdditionalInfo = PsdAdditionalInfo.Selective;
        WriteAndCheckProfile(images, defines, 152);

        defines.AdditionalInfo = PsdAdditionalInfo.None;
        WriteAndCheckProfile(images, defines, 0);
      }
    }
Esempio n. 10
0
    public static void ConvertPDFToMultipleImages()
    {
      MagickReadSettings settings = new MagickReadSettings();
      // Settings the density to 300 dpi will create an image with a better quality
      settings.Density = new PointD(300, 300);

      using (MagickImageCollection images = new MagickImageCollection())
      {
        // Add all the pages of the pdf file to the collection
        images.Read(SampleFiles.SnakewarePdf, settings);

        int page = 1;
        foreach (MagickImage image in images)
        {
          // Write page to file that contains the page number
          image.Write(SampleFiles.OutputDirectory + "Snakeware.Page" + page + ".png");
          // Writing to a specific format works the same as for a single image
          image.Format = MagickFormat.Ptif;
          image.Write(SampleFiles.OutputDirectory + "Snakeware.Page" + page + ".tif");
          page++;
        }
      }
    }
        public void ConvertToGrayScale(string sourceFile, string targetFile)
        {
            using (MagickImageCollection images = new MagickImageCollection())
            {
                string newTargetFile = @"D:\Development\Magik\Images\NewTiffs\New.tif";
                MagickReadSettings settings = new MagickReadSettings();
                images.Read(sourceFile, settings);
                settings.FrameIndex = 0; // First page
                settings.FrameCount = images.Count; // Number of pages
                int count = images.Count;

                foreach (MagickImage image in images)
                {
                    image.ColorType = ColorType.Grayscale;
                    image.Quantize();

                    image.Write(newTargetFile + count.ToString() + ".tif");
                    ++count;
                }
            }

            Process proc = new Process
            {
                StartInfo = new ProcessStartInfo

                {

                    FileName = @"C:\Program Files (x86)\ImageMagick-6.8.6-Q8\convert.exe",
                    Arguments = @"D:\Development\Magik\Images\NewTiffs\*.tif D:\Development\Magik\Images\Combined\all-in-one.tif",
                    UseShellExecute = false,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                }
            };

            proc.Start();
        }
    public void Test_Warning()
    {
      int count = 0;
      EventHandler<WarningEventArgs> warningDelegate = delegate (object sender, WarningEventArgs arguments)
      {
        Assert.IsNotNull(sender);
        Assert.IsNotNull(arguments);
        Assert.IsNotNull(arguments.Message);
        Assert.IsNotNull(arguments.Exception);
        Assert.AreNotEqual("", arguments.Message);

        count++;
      };

      using (MagickImageCollection collection = new MagickImageCollection())
      {
        collection.Warning += warningDelegate;
        collection.Read(Files.EightBimTIF);

        Assert.AreNotEqual(0, count);

        int expectedCount = count;
        collection.Warning -= warningDelegate;
        collection.Read(Files.EightBimTIF);

        Assert.AreEqual(expectedCount, count);
      }
    }
    public void Test_ToBase64()
    {
      using (MagickImageCollection collection = new MagickImageCollection())
      {
        Assert.AreEqual("", collection.ToBase64());

        collection.Read(Files.Builtin.Logo);
        Assert.AreEqual(1228800, collection.ToBase64(MagickFormat.Rgb).Length);
      }
    }
    public void Test_Append()
    {
      int width = 70;
      int height = 46;

      using (MagickImageCollection collection = new MagickImageCollection())
      {
        ExceptionAssert.Throws<InvalidOperationException>(delegate ()
        {
          collection.AppendHorizontally();
        });

        ExceptionAssert.Throws<InvalidOperationException>(delegate ()
        {
          collection.AppendVertically();
        });

        collection.Read(Files.RoseSparkleGIF);

        Assert.AreEqual(width, collection[0].Width);
        Assert.AreEqual(height, collection[0].Height);

        using (MagickImage image = collection.AppendHorizontally())
        {
          Assert.AreEqual(width * 3, image.Width);
          Assert.AreEqual(height, image.Height);
        }

        using (MagickImage image = collection.AppendVertically())
        {
          Assert.AreEqual(width, image.Width);
          Assert.AreEqual(height * 3, image.Height);
        }
      }
    }
    public void Test_Read()
    {
      MagickImageCollection collection = new MagickImageCollection();

      ExceptionAssert.Throws<ArgumentException>(delegate ()
      {
        collection.Read(new byte[0]);
      });

      ExceptionAssert.Throws<ArgumentNullException>(delegate ()
      {
        collection.Read((byte[])null);
      });

      ExceptionAssert.Throws<ArgumentNullException>(delegate ()
      {
        collection.Read((Stream)null);
      });

      ExceptionAssert.Throws<ArgumentNullException>(delegate ()
      {
        collection.Read((string)null);
      });

      ExceptionAssert.Throws<ArgumentException>(delegate ()
      {
        collection.Read(Files.Missing);
      });

      collection.Read(File.ReadAllBytes(Files.RoseSparkleGIF));
      Assert.AreEqual(3, collection.Count);

      using (FileStream fs = File.OpenRead(Files.RoseSparkleGIF))
      {
        collection.Read(fs);
        Assert.AreEqual(3, collection.Count);
      }

      collection.Read(Files.RoseSparkleGIF);
      Test_Read(collection);

      collection.Read(new FileInfo(Files.RoseSparkleGIF));

      collection.Dispose();
    }
    public void Test_Ping()
    {
      MagickImageCollection collection = new MagickImageCollection();

      ExceptionAssert.Throws<ArgumentException>(delegate ()
      {
        collection.Ping(new byte[0]);
      });

      ExceptionAssert.Throws<ArgumentNullException>(delegate ()
      {
        collection.Ping((byte[])null);
      });

      ExceptionAssert.Throws<ArgumentNullException>(delegate ()
      {
        collection.Ping((Stream)null);
      });

      ExceptionAssert.Throws<ArgumentNullException>(delegate ()
      {
        collection.Ping((string)null);
      });

      ExceptionAssert.Throws<ArgumentException>(delegate ()
      {
        collection.Ping(Files.Missing);
      });

      collection.Ping(Files.FujiFilmFinePixS1ProJPG);
      Test_Ping(collection);
      Assert.AreEqual(600, collection[0].Width);
      Assert.AreEqual(400, collection[0].Height);

      collection.Ping(new FileInfo(Files.FujiFilmFinePixS1ProJPG));
      Test_Ping(collection);
      Assert.AreEqual(600, collection[0].Width);
      Assert.AreEqual(400, collection[0].Height);

      collection.Ping(File.ReadAllBytes(Files.FujiFilmFinePixS1ProJPG));
      Test_Ping(collection);
      Assert.AreEqual(600, collection[0].Width);
      Assert.AreEqual(400, collection[0].Height);

      collection.Read(Files.SnakewarePNG);
      Assert.AreEqual(286, collection[0].Width);
      Assert.AreEqual(67, collection[0].Height);
      using (PixelCollection pixels = collection[0].GetPixels())
      {
        Assert.AreEqual(38324, pixels.ToArray().Length);
      }

      collection.Dispose();
    }
    public void Test_Merge()
    {
      using (MagickImageCollection collection = new MagickImageCollection())
      {
        ExceptionAssert.Throws<InvalidOperationException>(delegate ()
        {
          collection.Merge();
        });

        collection.Read(Files.RoseSparkleGIF);

        using (MagickImage first = collection.Merge())
        {
          Assert.AreEqual(collection[0].Width, first.Width);
          Assert.AreEqual(collection[0].Height, first.Height);
        }
      }
    }
    public void Test_Map()
    {
      using (MagickImageCollection colors = new MagickImageCollection())
      {
        colors.Add(new MagickImage(MagickColors.Red, 1, 1));
        colors.Add(new MagickImage(MagickColors.Green, 1, 1));

        using (MagickImage remapImage = colors.AppendHorizontally())
        {
          using (MagickImageCollection collection = new MagickImageCollection())
          {
            ExceptionAssert.Throws<InvalidOperationException>(delegate ()
            {
              collection.Map(null);
            });

            ExceptionAssert.Throws<InvalidOperationException>(delegate ()
            {
              collection.Map(remapImage);
            });

            collection.Read(Files.RoseSparkleGIF);

            ExceptionAssert.Throws<ArgumentNullException>(delegate ()
            {
              collection.Map(null);
            });

            QuantizeSettings settings = new QuantizeSettings();
            settings.DitherMethod = DitherMethod.FloydSteinberg;

            collection.Map(remapImage, settings);

            ColorAssert.AreEqual(MagickColors.Red, collection[0], 60, 17);
            ColorAssert.AreEqual(MagickColors.Green, collection[0], 37, 24);

            ColorAssert.AreEqual(MagickColors.Red, collection[1], 58, 30);
            ColorAssert.AreEqual(MagickColors.Green, collection[1], 36, 26);

            ColorAssert.AreEqual(MagickColors.Red, collection[2], 60, 40);
            ColorAssert.AreEqual(MagickColors.Green, collection[2], 17, 21);
          }
        }
      }
    }
    public void Test_Coalesce()
    {
      using (MagickImageCollection collection = new MagickImageCollection())
      {
        ExceptionAssert.Throws<InvalidOperationException>(delegate ()
        {
          collection.Coalesce();
        });

        collection.Read(Files.RoseSparkleGIF);

        using (PixelCollection pixels = collection[1].GetPixels())
        {
          MagickColor color = pixels.GetPixel(53, 3).ToColor();
          Assert.AreEqual(0, color.A);
        }

        collection.Coalesce();

        using (PixelCollection pixels = collection[1].GetPixels())
        {
          MagickColor color = pixels.GetPixel(53, 3).ToColor();
          Assert.AreEqual(Quantum.Max, color.A);
        }
      }
    }
Esempio n. 20
0
        public void SetupViewing()
        {
            FileInfo[] fi = ((DirectoryInfo)comboBox1.SelectedItem).GetFiles();
            if (fi.Length == 0)
            {
                throw new FileNotFoundException("В папке временного хранения для данного года и заглавия отсутствуют файлы!");
            }
            PDF = false;
            fPDF = fi[0];
            int PDFFileCount = 0;
            foreach (FileInfo f in fi)
            {
                if (f.Extension.Contains("pdf"))
                {
                    PDF = true;
                    fPDF = f;
                    PDFFileCount++;
                }
            }
            if (PDFFileCount > 1)
            {
                throw new Exception("Во временном хранении в указанном заглавии и годе более одного ПДФ-файла!");
            }
            if (PDF)//ЕСЛИ В ПАПКЕ ПДФ
            {
                lb = new List<Bitmap>();
                PdfReader reader = new PdfReader(fPDF.FullName);
                max_img = reader.NumberOfPages;
                max_img = (max_img < 10) ? max_img : 10;
                MagickReadSettings settings = new MagickReadSettings();
                settings.Density = new MagickGeometry(300, 300);//качество изображения
                settings.FrameIndex = 0; // Первая страница
                settings.FrameCount = 10; // Количество страниц. (10 значит 10, а не 11)

                using (MagickImageCollection images = new MagickImageCollection())
                {
                    images.Read(fPDF.FullName, settings);
                    for (int i = 0; i < max_img; i++)
                    {
                        lb.Add(images[i].ToBitmap());
                    }
                }
                pictureBox1.Image = lb[0];
                label1.Text = "Страница " + (current + 1).ToString() + " из " + max_img.ToString();
            }
            else // ЕСЛИ В ПАПКЕ КАРТИНКИ
            {
                lb = new List<Bitmap>();

                if (fi.Length >= 10)
                {
                    max_img = 10;
                }
                else
                {
                    max_img = fi.Length;
                }
                for (int i = 0; i < max_img; i++)
                {
                    lb.Add((Bitmap)Bitmap.FromFile(fi[i].FullName));
                }
                pictureBox1.Image = lb[0];
                label1.Text = "Страница " + (current + 1).ToString() + " из " + max_img.ToString();
            }
        }
Esempio n. 21
0
        public static FileInfo ConvertPdfToPng(FileInfo pdfFile)
        {
            if (pdfFile.DirectoryName == null)
                throw new ArgumentException("file directory was null. why?");

            MagickReadSettings imsettings = new MagickReadSettings
            {
                Density = new PointD(300, 300), // Settings the density to 300 dpi will create an image with a better quality
                FrameIndex = 0, // first page
                FrameCount = 1, // number of pages
                Format = MagickFormat.Pdf
            };

            const MagickFormat imageOutputFormat = MagickFormat.Png;
            var pngFilename = GetFileNameWithoutExtension(pdfFile) + "." + imageOutputFormat.ToString();
            var pngFile = new FileInfo(Path.Combine(pdfFile.DirectoryName, pngFilename));

            try
            {
                // note that this "collection" is a bunch of pages in a pdf, and actually only 1 because we are limiting it to page 1.
                using (var images = new MagickImageCollection())
                {
                    // Add all the pages of the pdf file to the collection
                    images.Read(pdfFile, imsettings);
                    foreach (var image in images)
                    {
                        image.Format = imageOutputFormat;
                        image.Write(pngFile);
                    }
                }
                return pngFile;
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                throw;
            }
        }
Esempio n. 22
0
    public static void ReadImageWithMultipleFrames()
    {
      // Read from file
      using (MagickImageCollection collection = new MagickImageCollection(SampleFiles.SnakewareJpg))
      {
      }

      // Read from stream
      using (MemoryStream memStream = LoadMemoryStreamImage())
      {
        using (MagickImageCollection collection = new MagickImageCollection(memStream))
        {
        }
      }

      // Read from byte array
      byte[] data = LoadImageBytes();
      using (MagickImageCollection collection = new MagickImageCollection(data))
      {
      }

      // Read pdf with custom density.
      MagickReadSettings settings = new MagickReadSettings();
      settings.Density = new PointD(144, 144);

      using (MagickImageCollection collection = new MagickImageCollection(SampleFiles.SnakewarePdf, settings))
      {
      }

      using (MagickImageCollection collection = new MagickImageCollection())
      {
        collection.Read(SampleFiles.SnakewareJpg);
        using (MemoryStream memStream = LoadMemoryStreamImage())
        {
          collection.Read(memStream);
        }
        collection.Read(data);
        collection.Read(SampleFiles.SnakewarePdf, settings);
      }
    }
Esempio n. 23
0
        private async void OnSelectedSourceFileChanged()
        {
            if (SelectedSourceFile == null ||
                !SelectedSourceFile.Exists)
                return;

            var settings = new MagickReadSettings
            {
                Density = new Density(150, 150),
                FrameIndex = 0,
                FrameCount = 1
            };

            var filename = Path.GetTempFileName();
            await Task.Run(() =>
            {
                try
                {
                    using (var images = new MagickImageCollection())
                    {
                        images.Read(SelectedSourceFile, settings);

                        var image = images.First();
                        image.Format = MagickFormat.Jpeg;
                        images.Write(filename);
                    }
                }
                catch (Exception ex)
                {
                    Log.Warn("Unable to preview document.", ex);
                    PreviewImage = null;
                    PreviewImageFilename = null;
                    SelectedFilePageCount = 0;
                }

                try
                {
                    using (var pdfReader = new PdfReader(SelectedSourceFile.FullName))
                        SelectedFilePageCount = pdfReader.NumberOfPages;
                }
                catch (Exception ex)
                {
                    Log.Warn("Unable to count pages.", ex);
                    SelectedFilePageCount = 0;
                }
            });

            try
            {
                var uri = new Uri(filename);
                var bitmap = new BitmapImage(uri);
                PreviewImage = bitmap;
                PreviewImageFilename = filename;
            }
            catch (Exception)
            {
                Log.Warn("Unable to preview selected document.");

                try
                {
                    var uri = new Uri("pack://application:,,,/PaperPusher;component/Art/unknown_icon_512.png");
                    var bitmap = new BitmapImage(uri);
                    PreviewImage = bitmap;
                }
                catch (Exception ex)
                {
                    Log.Error("Error showing unknown file icon.", ex);
                }
            }
        }
        public async Task<Boolean> Run(
            String pathToFile, 
            CreatePdfImageTaskParams createPdfImageTaskParams, 
            Func<int, Stream, Task<Boolean>> pageWriter)
        {
            String tempFileName = null;
            if (Passwords.Count > 0)
            {
                tempFileName = 
                    Path.Combine(Path.GetDirectoryName(pathToFile),
                    Path.GetFileNameWithoutExtension(pathToFile) + "_decrypted.pdf");
                if (Decryptor.DecryptFile(pathToFile, tempFileName, Passwords))
                {
                    pathToFile = tempFileName;
                }
            }
            using (var sourceStream = File.OpenRead(pathToFile))
            {
                var settings = new MagickReadSettings
                {
                    Density = new PointD(createPdfImageTaskParams.Dpi, createPdfImageTaskParams.Dpi)
                };
                settings.FrameIndex = 0; // First page
                settings.FrameCount = 1; // Number of pages
                MagickFormat imageFormat = TranslateFormat(createPdfImageTaskParams.Format);

                Logger.DebugFormat("Image format is {0}", imageFormat.ToString());
                using (var images = new MagickImageCollection())
                {
                    bool done = false;
                    if (_firstDone == false)
                    {
                        lock (LockForInitializationIssue)
                        {
                            if (_firstDone == false)
                            {
                                images.Read(sourceStream, settings);
                                done = true;
//                            _firstDone = true;
                            }
                        }
                    }

                    if (!done)
                        images.Read(sourceStream, settings);

                    var lastImage =
                        Math.Min(createPdfImageTaskParams.FromPage - 1 + createPdfImageTaskParams.Pages, images.Count) -
                        1;
                    for (int page = createPdfImageTaskParams.FromPage - 1; page <= lastImage; page++)
                    {
                        var image = images[page];
                        image.Format = imageFormat;

                        using (var ms = new MemoryStream())
                        {
                            image.Write(ms);
                            ms.Seek(0L, SeekOrigin.Begin);
                            await pageWriter(page + 1, ms);
                        }
                    }
                }
            }
            if (!String.IsNullOrEmpty(tempFileName) && File.Exists(tempFileName))
            {
                File.Delete(tempFileName);
            }
            return true;
        }
Esempio n. 25
0
    public static void ReadSinglePageFromPDF()
    {
      using (MagickImageCollection collection = new MagickImageCollection())
      {
        MagickReadSettings settings = new MagickReadSettings();
        settings.FrameIndex = 0; // First page
        settings.FrameCount = 1; // Number of pages

        // Read only the first page of the pdf file
        collection.Read(SampleFiles.SnakewarePdf, settings);

        // Clear the collection
        collection.Clear();

        settings.FrameCount = 2; // Number of pages

        // Read the first two pages of the pdf file
        collection.Read(SampleFiles.SnakewarePdf, settings);
      }
    }
Esempio n. 26
0
        private static void Convert(string filename, string outputPrefix, string outputDirectory, string outputFormat,
            Tuple<int, int> pageRange, Tuple<int, int> dpi, Tuple<int, int> geometry)
        {
            if (!File.Exists(filename))
            {
                Console.WriteLine("Unable to find file: {0}", filename);
                return;
            }

            filename = Path.GetFileName(filename);
            var ext = Path.GetExtension(filename);
            if (ext != ".pdf" && ext != ".pdfa")
            {
                Console.WriteLine("Invalid input format: {0}", ext);
                return;
            }

            if (!Directory.Exists(outputDirectory))
            {
                Console.WriteLine("Cannot find output directory: {0}", outputDirectory);
                return;
            }

            if (string.IsNullOrEmpty(outputFormat))
            {
                outputFormat = "png";
            }

            if (!IsSupportedFormat(outputFormat))
            {
                Console.WriteLine("Unsupported output format: {0}", outputFormat);
                return;
            }

            using (var collection = new MagickImageCollection())
            {
                Console.WriteLine("Reading {0}", filename);

                try
                {
                    var settings = new MagickReadSettings();
                    if (dpi != null)
                    {
                        settings.Density = new MagickGeometry(dpi.Item1, dpi.Item2);
                    }
                    if (geometry != null)
                    {
                        settings.Width = geometry.Item1;
                        settings.Height = geometry.Item2;
                    }
                    collection.Read(filename, settings);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Unable to read file: {0}", ex);
                }

                Console.WriteLine("Read {0} pages", collection.Count);

                int x = pageRange == null ? 0 : pageRange.Item1;
                int y = pageRange == null ? collection.Count : pageRange.Item2;

                int index = 0;
                foreach (var page in collection)
                {
                    if (!index.Between(x, y))
                    {
                        break;
                    }

                    try
                    {
                        Console.WriteLine("Converting page {0} to {1}", index, page.Format);

                        page.Write(Path.Combine(outputDirectory, string.Format("{0}{1}.{2}", outputPrefix, index, outputFormat)));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Unable to convert page on index {0}. Reason: {1}", index, ex.Message);
                    }

                    index++;
                }

            }
        }
Esempio n. 27
0
        private void CopyPDFToTarget(string ip, string sTarget, string sSource, FileInfo fPDF, int number, int total, fProgress fp,string sTargetConnectBookAddInf)
        {
            DirectoryInfo diTarget = new DirectoryInfo(sTarget);
            DirectoryInfo diSource = new DirectoryInfo(sSource);
            DirectoryInfo TargetFolder = new DirectoryInfo(sTarget + @"\" + this.Year.ToString() + @"\" + fPDF.Name.Remove(fPDF.Name.LastIndexOf(".")));
            string outside_ip = @"\\" + XmlConnections.GetConnection("/Connections/outside_ip") + @"\Backup\BookAddInf\PERIOD\";
            string PIN = PINFormat(this.PIN);

            outside_ip += PIN.Substring(0, 1) + @"\" + PIN.Substring(1, 3) + @"\" + PIN.Substring(4, 3) + @"\";
            DirectoryInfo TargetFolderOutside = new DirectoryInfo(outside_ip + @"\" + this.Year.ToString() + @"\" + fPDF.Name.Remove(fPDF.Name.LastIndexOf(".")));

            PdfReader reader = new PdfReader(fPDF.FullName);
            max_img = reader.NumberOfPages;
            if ((Package + fPDF.Name + ";").Length >= 3000)
            {
                PackageList.Add(Package);
                Package = "";
            }
            Package += fPDF.Name.Remove(fPDF.Name.LastIndexOf(".")) + ";";
            MagickReadSettings settings = new MagickReadSettings();
            using (new NetworkConnection(sTargetConnectBookAddInf, new NetworkCredential(@"bj\DigitCentreWork01", "DigCW_01")))
            {
                TargetFolder.Refresh();
            }

            if (!TargetFolder.Exists)
            {
                try
                {
                    TargetFolder.Create();
                }
                catch
                {
                    using (new NetworkConnection(sTargetConnectBookAddInf, new NetworkCredential(@"bj\DigitCentreWork01", "DigCW_01")))
                    {
                        TargetFolder.Create();
                    }
                }
            }
            else
            {
                MessageBox.Show("Такой файл уже добавлялся! Выберите другой файл!");
                fp.Close();
                this.Enabled = true;
                return;
            }
            /*using (new NetworkConnection(outside_ip, new NetworkCredential(@"bj\CopyPeriodAddInf", "Period_Copy")))
            {
                TargetFolderOutside.Refresh();
            }

            if (!TargetFolderOutside.Exists)
            {
                try
                {
                    TargetFolderOutside.Create();
                }
                catch
                {
                    using (new NetworkConnection(outside_ip, new NetworkCredential(@"bj\CopyPeriodAddInf", "Period_Copy")))
                    {
                        TargetFolderOutside.Create();
                    }
                }
            }*/
            using (MagickImageCollection images = new MagickImageCollection())
            {

                for (int i = 0; i < max_img; i++)
                {
                    settings.Density = new MagickGeometry(300, 300);//качество изображения
                    settings.FrameIndex = i; // Первая страница
                    settings.FrameCount = 1; // Количество страниц. (10 значит 10, а не 11)
                    images.Read(fPDF.FullName, settings);
                    DirectoryInfo To = new DirectoryInfo(TargetFolder.FullName);
                    DirectoryInfo ToOutside = new DirectoryInfo(TargetFolderOutside.FullName);

                    if (!To.Exists)
                    {
                        To.Create();
                    }
                    string fileTo = To.FullName + "\\" + i.ToString() + ".jpg";
                    //string fileToOutside = ToOutside.FullName + "\\" + i.ToString() + ".jpg";
                    try
                    {
                        images[0].ToBitmap().Save(fileTo);
                    }
                    catch
                    {
                        using (new NetworkConnection(sTargetConnectBookAddInf, new NetworkCredential(@"bj\DigitCentreWork01", "DigCW_01")))
                        {
                            images[0].ToBitmap().Save(fileTo);
                        }
                    }
                    /*try
                    {
                        images[0].ToBitmap().Save(fileToOutside);
                    }
                    catch
                    {
                        using (new NetworkConnection(outside_ip, new NetworkCredential(@"bj\CopyPeriodAddInf", "Period_Copy")))
                        {
                            images[0].ToBitmap().Save(fileToOutside);
                        }
                    }*/
                    //fp.IncProgress();
                    fp.IncProgress(total, i + 1, total);
                    Application.DoEvents();
                    GC.Collect();
                }
            }
            AddInfo();
        }
Esempio n. 28
0
		private static void ConvertImageToTiff()
		{
			// Log all events
			//MagickNET.SetLogEvents(LogEvents.All | LogEvents.Trace);
			// Set the log handler (all threads use the same handler)
			//MagickNET.Log += DetailedDebugInformationSamples.MagickNET_Log;


			string sampleDocsDirectory = @"E:\projects\ImageProcessing\sampledocs\";
			//string sampleFile = "sample1.pdf";
			string sampleFile = "sample2.pdf";
			//string sampleFile = "sample3.tif";
			//string sampleFile = "sample4.tif";
			//string sampleFile = "sample5.jpg";
			//string sampleFile = "sample6.pdf";

			try
			{
				MagickReadSettings settings = new MagickReadSettings();
				settings.Density = new PointD(300, 300);
				//settings.Density = new PointD(200, 200);
				//settings.Density = new PointD(192, 192);
				

				using (MagickImageCollection images = new MagickImageCollection())
				{
					// Add all the pages of the source file to the collection
					images.Read(Path.Combine(sampleDocsDirectory, sampleFile), settings);

					//Show page count
					Console.WriteLine("page count for {0} {1}", sampleFile, images.Count);

					//Base file name
					//string baseFileName = Guid.NewGuid().ToString();
					string baseFileName = Path.GetFileNameWithoutExtension(sampleFile);
					string fmtStr = GetPageNumberFormat(images.Count);
					int page = 1;
					foreach (MagickImage image in images)
					{
						switch (image.Format)
						{
							case MagickFormat.Jpeg:
							case MagickFormat.Jpg:
								image.CompressionMethod = CompressionMethod.LZW;
								break;
							case MagickFormat.Pdf:
								image.CompressionMethod = CompressionMethod.Group4;
								//image.CompressionMethod = CompressionMethod.LZW;
								break;
							case MagickFormat.Tif:
							case MagickFormat.Tiff:
							case MagickFormat.Tiff64:
								break;
							default:
								image.CompressionMethod = CompressionMethod.LZW;
								break;
						}
						
						//image.Format = MagickFormat.Tiff;
						Console.WriteLine("saving file: {0}", baseFileName + ".p" + page.ToString(fmtStr) + ".tif");
						image.Write(sampleDocsDirectory + baseFileName + ".p" + page.ToString(fmtStr) + ".tif");
						page++;
					}
				}

			}
			catch (Exception ex)
			{
				Console.WriteLine("ReadPdf error {0}", ex.Message);
			}
		}
Esempio n. 29
0
        private void SetupPreview()
        {
            lb = new List<Bitmap>();
            PdfReader reader = new PdfReader(fPDF.FullName);
            max_img = reader.NumberOfPages;
            max_img = (max_img < 10) ? max_img : 10;
            MagickReadSettings settings = new MagickReadSettings();
            settings.Density = new MagickGeometry(300, 300);//качество изображения
            settings.FrameIndex = 0; // Первая страница
            settings.FrameCount = 10; // Количество страниц. (10 значит 10, а не 11)

            using (MagickImageCollection images = new MagickImageCollection())
            {
                images.Read(fPDF.FullName, settings);
                for (int i = 0; i < max_img; i++)
                {
                    lb.Add(images[i].ToBitmap());
                }
            }
            pictureBox1.Image = lb[0];
            label1.Text = "Страница " + (current + 1).ToString() + " из " + max_img.ToString();
        }