이미지 작업

Aspose.Words사용자가 매우 유연한 방법으로 이미지를 작업 할 수 있습니다. 이 기사에서는 이미지 작업의 가능성 중 일부만 탐색 할 수 있습니다.

문서 {#how-to-extract-images-from-a-document}에서 이미지를 추출하는 방법

모든 이미지는 문서의Shape노드 안에 저장됩니다. 문서에서 특정 형식을 가진 모든 이미지 또는 이미지를 추출하려면 다음과 같이 하십시오:

  • getChildNodes메서드를 사용하여 모든 모양 노드를 선택합니다.
  • 결과 노드 컬렉션을 반복합니다.
  • hasImage부울 속성을 확인합니다.
  • ImageData속성을 사용하여 이미지 데이터를 추출합니다.
  • 이미지 데이터를 파일에 저장합니다.
// 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++;
}
}

각 문서 페이지에 바코드를 삽입하는 방법

이 예제에서는 워드 문서의 전체 또는 특정 페이지에 동일하거나 다른 바코드를 추가할 수 있습니다. 문서의 모든 페이지에 바코드를 추가하는 직접적인 방법은 없지만moveToSection,moveToHeaderFooterinsertImage방법을 사용하여 섹션이나 머리글/바닥글로 이동하고 다음 코드에서 볼 수 있듯이 바코드 이미지를 삽입 할 수 있습니다.

다음 코드 예제에서는 문서의 각 페이지에 바코드 이미지를 삽입하는 방법을 보여 줍니다:

// 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) {
}
}

이미지 {#lock-aspect-ratio-of-image}의 종횡비 잠금

기하학적 모양의 면 비율은 다른 차원의 크기의 비율입니다. AspectRatioLocked을 사용하여 이미지의 종횡비를 잠글 수 있습니다. 셰이프의 가로 세로 비율의 기본값은ShapeType에 따라 다릅니다. ShapeType.Image에 대해서는 참이고 다른 모양 유형에 대해서는 거짓입니다.

다음 코드 예제에서는 종횡비로 작업하는 방법을 보여 줍니다:

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

점 {#how-to-get-actual-bounds-of-shape-in-points}에서 모양의 실제 경계를 얻는 방법

페이지에 렌더링된 셰이프의 실제 경계 상자를 원하는 경우BoundsInPoints속성을 사용하여 이 작업을 수행할 수 있습니다.

다음 코드 예제에서는 이 속성을 사용하는 방법을 보여 줍니다:

// 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());

이미지 자르기

이미지의 자르기는 일반적으로 프레임을 개선하는 데 도움이되는 이미지의 원치 않는 외부 부분을 제거하는 것을 의미합니다. 또한 특정 영역에 초점을 맞추기 위해 이미지의 일부 부분을 제거하는 데 사용됩니다.

다음 코드 예제에서는Aspose.WordsAPI를 사용하여 이 작업을 수행하는 방법을 보여 줍니다:

// 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));
}

WMF으로 이미지 저장

Aspose.Words는 문서에서 사용 가능한 모든 이미지를 저장하는 기능을 제공합니다. WMFDOCX를RTF로 변환하는 동안 포맷합니다.

다음 코드 예제에서는RTF저장 옵션을 사용하여 이미지를WMF으로 저장하는 방법을 보여 줍니다:

// 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);