Работа с изображения
Aspose.Words позволява на потребителите да работят с изображения по много гъвкав начин. В тази статия можете да разгледате само някои от възможностите за работа с изображения.
Как да извлечете изображения от документ
Всички изображения се съхраняват вътре 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++; | |
} | |
} |
Как да въведете баркод на всяка страница с документи
Този пример ви позволява да добавите същите или различни баркоди на всички или конкретни страници на Word документ. Няма директен начин за добавяне на баркоди на всички страници на документ, но можете да използвате moveToSection, moveToHeaderFooter както и insertImage методи за преминаване към някоя секция или заглавни части/футове и вмъкване на баркод изображения, както можете да видите в следния код
Следният пример за код показва как да се постави изображение на баркод на всяка страница на документ:
// 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); |
Lock Aspect Съотношение на изображението
Съотношението на аспекта на геометрична форма е съотношението на неговите размери в различни размери. Можете да заключите съотношението на аспекта на изображение с помощта на AspectRatioLocked. Стойността по подразбиране на съотношението на аспекта на формата зависи от ShapeType. Така е. true вместо ShapeType.Image
както и false за други видове форми.
Следният пример за код показва как да се работи с отношението на аспекта:
// 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"); |
Как да получите действително границите на форма в точки
Ако искате действително свързваща кутия на формата, както е преведено на страницата, можете да постигнете това чрез използване на 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.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)); | |
} |
Запис на изображения като 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-Java | |
String fileName = "TestFile.doc"; | |
Document doc = new Document(dataDir + fileName); | |
RtfSaveOptions saveOpts = new RtfSaveOptions(); | |
saveOpts.setSaveImagesAsWmf(true); | |
doc.save(dataDir + "output.rtf", saveOpts); |