Bekerja dengan Gambar

Aspose.Words memungkinkan pengguna bekerja dengan gambar dengan cara yang sangat fleksibel. Pada artikel ini, Anda hanya dapat menjelajahi beberapa kemungkinan bekerja dengan gambar.

Memasukkan Gambar

DocumentBuilder menyediakan beberapa kelebihan metode insert_image yang memungkinkan Anda menyisipkan gambar sebaris atau mengambang. Jika gambar adalah metafile EMF atau WMF, maka akan dimasukkan ke dalam dokumen dalam format metafile. Semua gambar lainnya akan disimpan dalam format PNG. Metode masukkan_gambar dapat menggunakan gambar dari berbagai sumber:

  • Dari file atau URL dengan meneruskan parameter string
  • Dari aliran dengan meneruskan parameter Stream
  • Dari array byte dengan meneruskan parameter array byte

Untuk masing-masing metode masukkan_gambar, ada kelebihan lebih lanjut yang memungkinkan Anda menyisipkan gambar dengan opsi berikut:

  • Inline atau floating pada posisi tertentu, misalnya masukkan_gambar
  • Skala persentase atau ukuran khusus; selanjutnya, metode DocumentBuilder.insert_image mengembalikan objek Shape yang baru saja dibuat dan disisipkan sehingga Anda dapat memodifikasi properti Shape lebih lanjut

Memasukkan Gambar Sebaris

Berikan satu string yang mewakili file yang berisi gambar ke insert_image untuk menyisipkan gambar ke dalam dokumen sebagai grafik sebaris.

Contoh kode berikut menunjukkan cara menyisipkan gambar sebaris pada posisi kursor ke dalam dokumen:

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")

Memasukkan Gambar Mengambang (Diposisikan Secara Absolut)

Contoh kode berikut menunjukkan cara menyisipkan gambar mengambang dari file atau URL pada posisi dan ukuran tertentu:

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")

Cara Mengekstrak Gambar dari Dokumen

Semua gambar disimpan di dalam node Shape di Document. Untuk mengekstrak semua gambar atau gambar dengan tipe tertentu dari dokumen, ikuti langkah-langkah berikut:

Contoh kode berikut menunjukkan cara mengekstrak gambar dari dokumen dan menyimpannya sebagai file:

Anda dapat mengunduh file template contoh ini dari Di Sini.

# 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

Cara Menyisipkan Barcode pada Setiap Halaman Dokumen

Contoh ini menunjukkan Anda untuk menambahkan kode batang yang sama atau berbeda pada semua atau halaman tertentu pada dokumen Word. Tidak ada cara langsung untuk menambahkan barcode pada semua halaman dokumen tetapi Anda dapat menggunakan metode move_to_section, move_to_header_footer dan insert_image untuk berpindah ke bagian atau header/footer mana pun dan menyisipkan gambar barcode seperti yang Anda lihat pada kode berikut.

Contoh kode berikut Menyisipkan gambar barcode pada setiap halaman dokumen.

# 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")

Kunci Rasio Aspek Gambar

Rasio aspek suatu bentuk geometris adalah rasio ukurannya dalam dimensi yang berbeda. Anda dapat mengunci rasio aspek gambar menggunakan aspect_ratio_locked. Nilai default rasio aspek bentuk bergantung pada ShapeType. Ini adalah True untuk ShapeType.IMAGE dan False untuk tipe bentuk lainnya.

Contoh kode berikut menunjukkan cara bekerja dengan rasio aspek:

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")

Bagaimana Mendapatkan Batasan Bentuk Sebenarnya dalam Poin

Jika Anda menginginkan kotak pembatas sebenarnya dari bentuk seperti yang dirender pada halaman, Anda dapat mencapainya dengan menggunakan properti bounds_in_points.

Contoh kode berikut menunjukkan cara menggunakan properti ini:

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}")

Pangkas Gambar

Pemotongan gambar biasanya mengacu pada penghapusan bagian luar gambar yang tidak diinginkan untuk membantu menyempurnakan pembingkaian. Ini juga digunakan untuk menghilangkan beberapa bagian gambar guna meningkatkan fokus pada area tertentu.

Contoh kode berikut menunjukkan cara mencapai hal ini menggunakan 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))

Menyimpan Gambar sebagai WMF

Aspose.Words menyediakan fungsionalitas untuk menyimpan semua gambar yang tersedia dalam dokumen ke format WMF sambil mengonversi DOCX ke RTF.

Contoh kode berikut menunjukkan cara menyimpan gambar sebagai WMF dengan opsi penyimpanan 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)