Как получить размер картинки, изменить его и сохранить документ обратно в C# и .NET

  1. Добавьте SautinSoft.Document из Nuget.
  2. Загрузите документ DOCX.
  3. Найдите картинку.
  4. Измените размер картинки.
  5. Сохраните документ обратно.

Полный код

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
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/

            GetAndChangePictureSize();
        }

        /// <summary>
        /// Get a Picture size, Change it and Save the document back.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/get-and-change-picture-size-in-docx-csharp-vb-net.php
        /// </remarks>
        public static void GetAndChangePictureSize()
        {
            // Path to a document where to extract pictures.
            string inpFile = @"..\..\..\example.docx";
            string outFile = "Result.docx";

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

            // Get the physical size of the first picture from the document.            
            Picture pict = dc.GetChildElements(true, ElementType.Picture).FirstOrDefault() as Picture;
            Size size = pict.Layout.Size;

            Console.WriteLine("The 1st picture has this size:\r\n");
            Console.WriteLine("W: {0}, H: {1} (In points)", size.Width, size.Height);
            Console.WriteLine("W: {0}, H: {1} (In pixels)", LengthUnitConverter.Convert(size.Width, LengthUnit.Point, LengthUnit.Pixel),
                                                            LengthUnitConverter.Convert(size.Height, LengthUnit.Point, LengthUnit.Pixel));
            Console.WriteLine("W: {0:F2}, H: {1:F2} (In mm)", LengthUnitConverter.Convert(size.Width, LengthUnit.Point, LengthUnit.Millimeter),
                                                            LengthUnitConverter.Convert(size.Height, LengthUnit.Point, LengthUnit.Millimeter));
            Console.WriteLine("W: {0:F2}, H: {1:F2} (In cm)", LengthUnitConverter.Convert(size.Width, LengthUnit.Point, LengthUnit.Centimeter),
                                                            LengthUnitConverter.Convert(size.Height, LengthUnit.Point, LengthUnit.Centimeter));
            Console.WriteLine("W: {0:F2}, H: {1:F2} (In inches)", LengthUnitConverter.Convert(size.Width, LengthUnit.Point, LengthUnit.Inch),
                                                            LengthUnitConverter.Convert(size.Height, LengthUnit.Point, LengthUnit.Inch));

            Console.WriteLine("\r\nNow let\'s increase the picture size in x1.5 times. Press any key ...");
            Console.ReadKey();

            // Note, we don't change the physical picture size  we only scale/stretch the it.
            pict.Layout.Size = new Size(size.Width * 1.5, size.Height * 1.5);

            // Save the document as a new docx file.
            dc.Save(outFile);

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

        }
    }
}

Download

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

Module Sample
    Sub Main()
        GetAndChangePictureSize()
    End Sub
    ''' Get your free 30-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' Get a Picture size, Change it and Save the document back.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/get-and-change-picture-size-in-docx-csharp-vb-net.php
    ''' </remarks>
    Public Sub GetAndChangePictureSize()
        ' Path to a document where to extract pictures.
        Dim inpFile As String = "..\..\..\example.docx"
        Dim outFile As String = "Result.docx"


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

        ' Get the physical size of the first picture from the document.            
        Dim pict As Picture = TryCast(dc.GetChildElements(True, ElementType.Picture).FirstOrDefault(), Picture)
        Dim size As Size = pict.Layout.Size

        Console.WriteLine("The 1st picture has this size:" & vbCrLf)
        Console.WriteLine("W: {0}, H: {1} (In points)", size.Width, size.Height)
        Console.WriteLine("W: {0}, H: {1} (In pixels)", LengthUnitConverter.Convert(size.Width, LengthUnit.Point, LengthUnit.Pixel), LengthUnitConverter.Convert(size.Height, LengthUnit.Point, LengthUnit.Pixel))
        Console.WriteLine("W: {0:F2}, H: {1:F2} (In mm)", LengthUnitConverter.Convert(size.Width, LengthUnit.Point, LengthUnit.Millimeter), LengthUnitConverter.Convert(size.Height, LengthUnit.Point, LengthUnit.Millimeter))
        Console.WriteLine("W: {0:F2}, H: {1:F2} (In cm)", LengthUnitConverter.Convert(size.Width, LengthUnit.Point, LengthUnit.Centimeter), LengthUnitConverter.Convert(size.Height, LengthUnit.Point, LengthUnit.Centimeter))
        Console.WriteLine("W: {0:F2}, H: {1:F2} (In inches)", LengthUnitConverter.Convert(size.Width, LengthUnit.Point, LengthUnit.Inch), LengthUnitConverter.Convert(size.Height, LengthUnit.Point, LengthUnit.Inch))

        Console.WriteLine(vbCrLf & "Now let's increase the picture size in x1.5 times. Press any key ...")
        Console.ReadKey()

        ' Note, we don't change the physical picture size  we only scale/stretch the it.
        pict.Layout.Size = New Size(size.Width * 1.5, size.Height * 1.5)

        ' Save the document as a new docx file.
        dc.Save(outFile)

        ' Open the result for demonstration purposes.
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) With {.UseShellExecute = True})

    End Sub
End Module

Download


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



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

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