Как извлечь все изображения из документа с помощью C# и .NET

  1. Добавьте SautinSoft.Document из Nuget.
  2. Загрузите PDF-документ.
  3. Извлеките все изображения из документа.
  4. Сохраните все изображения.

Полный код

using System;
using System.IO;
using System.Collections.Generic;
using SautinSoft.Document;
using SautinSoft.Document.Drawing;

namespace Sample
{
    class Sample
    {
        
        static void Main(string[] args)
        {
            // Get your free 30-day key here:   
            // https://sautinsoft.com/start-for-free/

            ExtractPictures();
        }
		
        /// <summary>
        /// Extract all pictures from document (PDF, DOCX, RTF, HTML).
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/extract-pictures.php
        /// </remarks>
        public static void ExtractPictures()
        {
            // Path to a document where to extract pictures.
            string filePath = @"..\..\..\example.pdf";
           
            // Directory to store extracted pictures:
            DirectoryInfo imgDir = new DirectoryInfo("Extracted Pictures");
            imgDir.Create();
            string imgTemplateName = "Picture";

            // Here we store extracted images.
            List<ImageData> imgInventory = new List<ImageData>();

            // Load the document.
            DocumentCore dc = DocumentCore.Load(filePath);

            // Extract all images from document, skip duplicates.
            foreach (Picture pict in dc.GetChildElements(true, ElementType.Picture))
            {
                // Let's avoid the adding of duplicates.
                if (imgInventory.Exists((img => (img.GetStream().Length == pict.ImageData.GetStream().Length))) == false)
                    imgInventory.Add(pict.ImageData);
            }
            
            // Save all images.
            for (int i = 0; i < imgInventory.Count; i++)
            {
                string imagePath = Path.Combine(imgDir.FullName, String.Format("{0}{1}.{2}", imgTemplateName, i + 1, imgInventory[i].Format.ToString().ToLower()));
                File.WriteAllBytes(imagePath, imgInventory[i].GetStream().ToArray());                
            }

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(imgDir.FullName) { UseShellExecute = true });

        }
    }
}

Download

Imports System
Imports System.IO
Imports System.Collections.Generic
Imports SautinSoft.Document
Imports SautinSoft.Document.Drawing

Module Sample
    Sub Main()
        ExtractPictures()
    End Sub
    ''' Get your free 30-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' Extract all pictures from document (PDF, DOCX, RTF, HTML).
    ''' </summary>
    ''' <remarks>
    ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/extract-pictures.php
    ''' </remarks>
    Sub ExtractPictures()
        ' Path to a document where to extract pictures.
        Dim filePath As String = "..\..\..\example.pdf"

        ' Directory to store extracted pictures:
        Dim imgDir As New DirectoryInfo("Extracted Pictures")
        imgDir.Create()
        Dim imgTemplateName As String = "Picture"

        ' Here we store extracted images.
        Dim imgInventory As New List(Of ImageData)()

        ' Load the document.
        Dim dc As DocumentCore = DocumentCore.Load(filePath)

        ' Extract all images from document, skip duplicates.
        For Each pict As Picture In dc.GetChildElements(True, ElementType.Picture)
            ' Let's avoid the adding of duplicates.
            If imgInventory.Exists((Function(img) (img.GetStream().Length = pict.ImageData.GetStream().Length))) = False Then
                imgInventory.Add(pict.ImageData)
            End If
        Next pict

        ' Save all images.
        For i As Integer = 0 To imgInventory.Count - 1
            Dim imagePath As String = Path.Combine(imgDir.FullName, String.Format("{0}{1}.{2}", imgTemplateName, i + 1, imgInventory(i).Format.ToString().ToLower()))
            File.WriteAllBytes(imagePath, imgInventory(i).GetStream().ToArray())
        Next i

        ' Open the result for demonstration purposes.
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(imgDir.FullName) With {.UseShellExecute = True})
    End Sub
End Module

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.