Работа с изображениями

Aspose.Words позволяет пользователям работать с изображениями очень гибким способом. В этой статье вы можете рассмотреть лишь некоторые возможности работы с изображениями.

Вставка изображения

DocumentBuilder содержит несколько дополнений к методу insert_image, который позволяет вставлять встроенное или плавающее изображение. Если изображение представляет собой метафайл EMF или WMF, оно будет вставлено в документ в формате метафайла. Все остальные изображения будут сохранены в формате PNG. В методе insert_image можно использовать изображения из разных источников:

  • Из файла или URL путем передачи строкового параметра
  • Из потока путем передачи параметра Stream
  • Из массива байтов путем передачи параметра массива байтов

Для каждого из методов insert_image существуют дополнительные перегрузки, которые позволяют вставлять изображение со следующими параметрами:

  • Встроенный или плавающий в определенном положении, например, insert_image
  • Процентная шкала или пользовательский размер; кроме того, метод DocumentBuilder.insert_image возвращает объект Shape, который был только что создан и вставлен, чтобы вы могли дополнительно изменять свойства объекта Shape

Вставка встроенного изображения

Передайте одну строку, представляющую файл, содержащий изображение, в insert_image, чтобы вставить изображение в документ в виде встроенного графического изображения.

В следующем примере кода показано, как вставить встроенное изображение в положение курсора в документе:

doc = aw.Document()
builder = aw.DocumentBuilder(doc)

builder.insert_image(docs_base.images_dir + "Logo.jpg")

doc.save(docs_base.artifacts_dir+"WorkingWithImages.document_builder_insert_inline_image.doc")

Вставка плавающего (абсолютно расположенного) Изображение

В следующем примере кода показано, как вставить плавающее изображение из файла или URL в указанное положение и размер:

doc = aw.Document()
builder = aw.DocumentBuilder(doc)

builder.insert_image(docs_base.images_dir + "Logo.jpg",
    aw.drawing.RelativeHorizontalPosition.MARGIN,
    100,
    aw.drawing.RelativeVerticalPosition.MARGIN,
    100,
    200,
    100,
    aw.drawing.WrapType.SQUARE)

doc.save(docs_base.artifacts_dir+"WorkingWithImages.document_builder_insert_floating_image.doc")

Как извлечь изображения из документа

Все изображения хранятся внутри Shape узлов в Document. Чтобы извлечь из документа все изображения или картинки определенного типа, выполните следующие действия:

  • Используйте метод Document.get_child_nodes, чтобы выбрать все узлы Shape.
  • Выполните итерацию по результирующим наборам узлов.
  • Проверьте логическое свойство Shape.has_image.
  • Извлеките данные изображения, используя свойство Shape.image_data.
  • Сохраните данные изображения в файл.

В следующем примере кода показано, как извлекать изображения из документа и сохранять их в виде файлов:

Вы можете скачать файл шаблона для этого примера с сайта здесь.

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET
doc = aw.Document(docs_base.my_dir + "Images.docx")
shapes = doc.get_child_nodes(aw.NodeType.SHAPE, True)
imageIndex = 0
for shape in shapes :
shape = shape.as_shape()
if (shape.has_image) :
imageFileName = f"Image.ExportImages.{imageIndex}_{aw.FileFormatUtil.image_type_to_extension(shape.image_data.image_type)}"
shape.image_data.save(docs_base.artifacts_dir + imageFileName)
imageIndex += 1

Как вставить штрих-код на каждую страницу документа

В этом примере показано, как можно добавлять одинаковые или разные штрих-коды на все или определенные страницы документа Word. Прямого способа добавить штрих-коды на все страницы документа не существует, но вы можете использовать методы move_to_section, move_to_header_footer и insert_image, чтобы перейти к любому разделу или верхним/нижним колонтитулам и вставить изображения штрих-кодов, как вы можете видеть в следующем коде.

В следующем примере кода изображение штрих-кода вставляется на каждую страницу документа.

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET
doc = aw.Document()
builder = aw.DocumentBuilder(doc)
# The number of pages the document should have
numPages = 4
# The document starts with one section, insert the barcode into this existing section
self.insert_barcode_into_footer(builder, doc.first_section, aw.HeaderFooterType.FOOTER_PRIMARY)
for i in range(1, numPages) :
# Clone the first section and add it into the end of the document
cloneSection = doc.first_section.clone(False).as_section()
cloneSection.page_setup.section_start = aw.SectionStart.NEW_PAGE
doc.append_child(cloneSection)
# Insert the barcode and other information into the footer of the section
self.insert_barcode_into_footer(builder, cloneSection, aw.HeaderFooterType.FOOTER_PRIMARY)
# Save the document as a PDF to disk
# You can also save this directly to a stream
doc.save(docs_base.artifacts_dir + "InsertBarcodeImage.docx")
# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET
@staticmethod
def insert_barcode_into_footer(builder : aw.DocumentBuilder, section : aw.Section, footerType : aw.HeaderFooterType) :
# Move to the footer type in the specific section.
builder.move_to_section(section.document.index_of(section))
builder.move_to_header_footer(footerType)
# Insert the barcode, then move to the next line and insert the ID along with the page number.
# Use pageId if you need to insert a different barcode on each page. 0 = First page, 1 = Second page etc.
builder.insert_image(docs_base.images_dir + "Barcode.png")
builder.writeln()
builder.write("1234567890")
builder.insert_field("PAGE")
# Create a right-aligned tab at the right margin.
tabPos = section.page_setup.page_width - section.page_setup.right_margin - section.page_setup.left_margin
builder.current_paragraph.paragraph_format.tab_stops.add(aw.TabStop(tabPos, aw.TabAlignment.RIGHT, aw.TabLeader.NONE))
# Move to the right-hand side of the page and insert the page and page total.
builder.write(aw.ControlChar.TAB)
builder.insert_field("PAGE")
builder.write(" of ")
builder.insert_field("NUMPAGES")

Фиксируйте соотношение сторон изображения

Соотношение сторон геометрической фигуры - это соотношение ее размеров в разных измерениях. Вы можете настроить соотношение сторон изображения, используя aspect_ratio_locked. Значение соотношения сторон фигуры по умолчанию зависит от ShapeType. Это True для ShapeType.IMAGE и False для других типов фигур.

В следующем примере кода показано, как работать с соотношением сторон:

doc = aw.Document()
builder = aw.DocumentBuilder(doc)

shape = builder.insert_image(docs_base.images_dir + "Logo.jpg")
shape.aspect_ratio_locked = False

doc.save(docs_base.artifacts_dir+"WorkingWithImages.set_aspect_ratio_locked.doc")

Как получить фактические границы формы в точках

Если вы хотите, чтобы фактическая ограничивающая рамка фигуры отображалась на странице, вы можете добиться этого с помощью свойства bounds_in_points.

В следующем примере кода показано, как использовать это свойство:

doc = aw.Document()
builder = aw.DocumentBuilder(doc)

shape = builder.insert_image(docs_base.images_dir + "Logo.jpg")
shape.aspect_ratio_locked = False

print("\nGets the actual bounds of the shape in points.")
rect = shape.get_shape_renderer().bounds_in_points
print(f"{rect.x}, {rect.y}, {rect.width}, {rect.height}")

Обрезка изображений

Обрезка изображения обычно означает удаление нежелательных внешних частей изображения, чтобы улучшить качество кадрирования. Она также используется для удаления некоторых частей изображения, чтобы увеличить фокусировку на определенной области.

В следующем примере кода показано, как этого добиться, используя Aspose.Words API:

# The path to the documents directory.
inputPath = docs_base.images_dir + "Logo.jpg"
outputPath = docs_base.artifacts_dir + "cropped_logo.jpg"

self.crop_image(inputPath,outputPath, 100, 90, 200, 200)
@staticmethod
def crop_image(inPath : str, outPath : str, left : int, top : int, width : int, height : int) :
    
    doc = aw.Document();
    builder = aw.DocumentBuilder(doc)
    
    croppedImage = builder.insert_image(inPath)
    
    src_width_points = croppedImage.width
    src_height_points = croppedImage.height
    
    croppedImage.width = aw.ConvertUtil.pixel_to_point(width)
    croppedImage.height = aw.ConvertUtil.pixel_to_point(height)
    
    widthRatio = croppedImage.width / src_width_points
    heightRatio = croppedImage.height / src_height_points
    
    if (widthRatio< 1) :
        croppedImage.image_data.crop_right = 1 - widthRatio
    
    if (heightRatio< 1) :
        croppedImage.image_data.crop_bottom = 1 - heightRatio
    
    leftToWidth = aw.ConvertUtil.pixel_to_point(left) / src_width_points
    topToHeight = aw.ConvertUtil.pixel_to_point(top) / src_height_points
    
    croppedImage.image_data.crop_left = leftToWidth
    croppedImage.image_data.crop_right = croppedImage.image_data.crop_right - leftToWidth
    
    croppedImage.image_data.crop_top = topToHeight
    croppedImage.image_data.crop_bottom = croppedImage.image_data.crop_bottom - topToHeight
    
    croppedImage.get_shape_renderer().save(outPath, aw.saving.ImageSaveOptions(aw.SaveFormat.JPEG))

Сохранение изображений как WMF

Aspose.Words предоставляет функциональные возможности для сохранения всех доступных изображений в документе в WMF форматируйте при преобразовании DOCX в RTF.

В следующем примере кода показано, как сохранять изображения как WMF с параметрами сохранения RTF:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET
doc = aw.Document(docs_base.my_dir + "Document.docx")
saveOptions = aw.saving.RtfSaveOptions()
saveOptions.save_images_as_wmf = True
doc.save(docs_base.artifacts_dir + "WorkingWithRtfSaveOptions.saving_images_as_wmf.rtf", saveOptions)