العمل مع الصور

يتيح Aspose.Words للمستخدمين العمل مع الصور بطريقة مرنة للغاية. في هذه المقالة، يمكنك استكشاف بعض إمكانيات العمل مع الصور فقط.

إدراج صورة

يوفر DocumentBuilder العديد من التحميلات الزائدة لطريقة insert_image التي تسمح لك بإدراج صورة مضمّنة أو عائمة. إذا كانت الصورة عبارة عن ملف تعريف EMF أو WMF، فسيتم إدراجها في المستند بتنسيق ملف تعريف. سيتم تخزين جميع الصور الأخرى بتنسيق PNG. يمكن لطريقة إدراج صورة استخدام صور من مصادر مختلفة:

  • من ملف أو URL عن طريق تمرير معلمة سلسلة
  • من الدفق عن طريق تمرير معلمة Stream
  • من صفيف بايت عن طريق تمرير معلمة صفيف بايت

لكل طريقة من طرق إدراج صورة، هناك المزيد من التحميلات الزائدة التي تسمح لك بإدراج صورة بالخيارات التالية:

  • مضمنة أو عائمة في موضع محدد، على سبيل المثال، إدراج صورة
  • مقياس النسبة المئوية أو الحجم المخصص؛ علاوة على ذلك، تقوم طريقة 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 وظيفة لحفظ جميع الصور المتوفرة في مستند بتنسيق ومف أثناء تحويل 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)