Làm việc với hình ảnh

Aspose.Words" cho phép người dùng làm việc với hình ảnh theo một cách rất linh hoạt. Trong bài viết này, bạn chỉ có thể khám phá một số khả năng làm việc với hình ảnh.

Cách Lấy Ảnh ra từ Tài liệu

Tất cả hình ảnh được lưu trữ bên trong các Shape node trong một tài liệu. Để trích xuất tất cả các hình ảnh hoặc hình ảnh có một loại cụ thể từ tài liệu, làm theo các bước sau:

  • Sử dụng getChildNodes phương pháp để chọn tất cả các node hình dạng.
  • Lặp qua các bộ sưu tập nút.
  • Kiểm tra thuộc tính hasImage boolean.
  • Lấy dữ liệu ảnh bằng thuộc tính ImageData. Lưu dữ liệu hình ảnh vào tập tin.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ExtractImagesToFiles.class);
Document doc = new Document(dataDir + "Image.SampleImages.doc");
NodeCollection<Shape> shapes = (NodeCollection<Shape>) doc.getChildNodes(NodeType.SHAPE, true);
int imageIndex = 0;
for (Shape shape : shapes
) {
if (shape.hasImage()) {
String imageFileName = String.format(
"Image.ExportImages.{0}_out_{1}", imageIndex, FileFormatUtil.imageTypeToExtension(shape.getImageData().getImageType()));
shape.getImageData().save(dataDir + imageFileName);
imageIndex++;
}
}

Cách chèn mã vạch trên mỗi trang tài liệu

Ví dụ này cho phép bạn thêm cùng một hoặc các mã vạch khác nhau trên tất cả hoặc các trang cụ thể trong tài liệu Word. Không có cách trực tiếp nào để thêm mã vạch trên tất cả các trang của một tài liệu nhưng bạn có thể sử dụng moveToSection, moveToHeaderFooter và [insertImage](https://reference.aspose.com/words/java/com.aspose.words/DocumentBuilder#insertImage(byte[]) các phương pháp để di chuyển đến bất kỳ phần nào hoặc tiêu đề/chân trang và chèn hình ảnh mã vạch như bạn có thể thấy trong đoạn mã sau

Mã ví dụ sau cho thấy cách chèn một hình ảnh mã vạch vào mỗi trang trong một tài liệu:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(InsertBarcodeImage.class);
Document doc = new Document(dataDir + "Image.SampleImages.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
// The number of pages the document should have.
int numPages = 4;
// The document starts with one section, insert the barcode into this existing section.
InsertBarcodeIntoFooter(builder, doc.getFirstSection(), 1, HeaderFooterType.FOOTER_PRIMARY);
InsertBarcodeIntoFooter(builder, doc.getFirstSection(), 1, HeaderFooterType.FOOTER_PRIMARY);
for (int i = 1; i < numPages; i++) {
// Clone the first section and add it into the end of the document.
Section cloneSection = (Section) doc.getFirstSection().deepClone(false);
// cloneSection.getPageSetup().getSectionStart() = SectionStart.NEW_PAGE;
doc.appendChild(cloneSection);
// Insert the barcode and other information into the footer of the section.
InsertBarcodeIntoFooter(builder, cloneSection, i, HeaderFooterType.FOOTER_PRIMARY);
}
dataDir = dataDir + "Document_out_.docx";
// Save the document as a PDF to disk. You can also save this directly to a stream.
doc.save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
private static void InsertBarcodeIntoFooter(DocumentBuilder builder, Section section, int pageId, int footerType) {
// Move to the footer type in the specific section.
try {
builder.moveToSection(section.getDocument().indexOf(section));
builder.moveToHeaderFooter(footerType);
String dataDir = Utils.getDataDir(InsertBarcodeImage.class);
// 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.insertImage(dataDir + "Barcode1.png");
builder.writeln();
builder.write("1234567890");
builder.insertField("PAGE");
// Create a right aligned tab at the right margin.
double tabPos = section.getPageSetup().getPageWidth() - section.getPageSetup().getRightMargin() - section.getPageSetup().getLeftMargin();
builder.getCurrentParagraph().getParagraphFormat().getTabStops().add(new TabStop(tabPos, TabAlignment.RIGHT, TabLeader.NONE));
// Move to the right hand side of the page and insert the page and page total.
builder.write(ControlChar.TAB);
builder.insertField("PAGE");
builder.write(" of ");
builder.insertField("NUMPAGES");
} catch (Exception x) {
}
}

Khóa tỷ số khung hình của hình ảnh

Tỷ lệ khung hình của một hình học là tỷ lệ của kích thước ở các chiều khác nhau. Bạn có thể khóa tỷ lệ khung hình của một hình ảnh bằng AspectRatioLocked. Giá trị mặc định của tỷ số hình phụ thuộc vào ShapeType. Đó là true cho ShapeType.Image và false cho các kiểu hình dạng khác.

Mảnh mã ví dụ sau cho thấy cách làm việc với tỉ lệ khía cạnh:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(DocumentBuilderSetImageAspectRatioLocked.class);
// Open the document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = builder.insertImage(dataDir + "Test.png");
shape.setAspectRatioLocked(false);
doc.save(dataDir + "output.doc");

Cách lấy giới hạn thực của hình dạng trong điểm

Nếu bạn muốn hộp giới hạn thực tế của hình dạng được hiển thị trên trang, bạn có thể đạt được điều đó bằng cách sử dụng thuộc tính BoundsInPoints.

Ví dụ mã sau cho thấy cách sử dụng thuộc tính này:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = builder.insertImage(dataDir + "Test.png");
shape.setAspectRatioLocked(false);
System.out.print("\nGets the actual bounds of the shape in points. ");
System.out.println(shape.getShapeRenderer().getBoundsInPoints());

Cắt hình ảnh

Lấy cạnh của một hình ảnh thường đề cập đến việc loại bỏ các phần ngoài không mong muốn của một hình ảnh để giúp cải thiện khung hình. Nó cũng được dùng để loại bỏ một số phần của một hình ảnh để tăng sự tập trung vào một khu vực nhất định.

Ví dụ mã sau cho thấy cách để đạt được điều này bằng Aspose.Words API":

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CropImages.class);
String inputPath = dataDir + "ch63_Fig0013.jpg";
String outputPath = dataDir + "cropped-1.jpg";
cropImage(inputPath, outputPath, 124, 90, 570, 571);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
public static void cropImage(String inPath, String outPath, int left, int top, int width, int height) throws Exception {
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
BufferedImage img = ImageIO.read(new File(inPath));
int effectiveWidth = img.getWidth() - width;
int effectiveHeight = img.getHeight() - height;
Shape croppedImage = builder.insertImage(img,
ConvertUtil.pixelToPoint(img.getWidth() - effectiveWidth),
ConvertUtil.pixelToPoint(img.getHeight() - effectiveHeight));
double widthRatio = croppedImage.getWidth() / ConvertUtil.pixelToPoint(img.getWidth());
double heightRatio = croppedImage.getHeight() / ConvertUtil.pixelToPoint(img.getHeight());
if (widthRatio < 1)
croppedImage.getImageData().setCropRight(1 - widthRatio);
if (heightRatio < 1)
croppedImage.getImageData().setCropBottom(1 - heightRatio);
float leftToWidth = (float) left / img.getWidth();
float topToHeight = (float) top / img.getHeight();
croppedImage.getImageData().setCropLeft(leftToWidth);
croppedImage.getImageData().setCropRight(croppedImage.getImageData().getCropRight() - leftToWidth);
croppedImage.getImageData().setCropTop(topToHeight);
croppedImage.getImageData().setCropBottom(croppedImage.getImageData().getCropBottom() - topToHeight);
croppedImage.getShapeRenderer().save(outPath, new ImageSaveOptions(SaveFormat.JPEG));
}

Lưu hình ảnh thành WMF

Aspose.Words cung cấp chức năng để lưu tất cả các hình ảnh có sẵn trong một tài liệu sang WMF định dạng khi chuyển đổi từ DOCX sang RTF.

Ví dụ về đoạn mã sau cho thấy cách lưu hình ảnh dưới dạng WMF với các tùy chọn lưu RTF:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
String fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
RtfSaveOptions saveOpts = new RtfSaveOptions();
saveOpts.setSaveImagesAsWmf(true);
doc.save(dataDir + "output.rtf", saveOpts);