Работа с изображениями

Aspose.Words Это позволяет пользователям работать с изображениями очень гибко. В этой статье вы можете изучить только некоторые возможности работы с изображениями.

Как вставить изображение

DocumentBuilder Это приводит к нескольким перегрузкам InsertImage Способ, позволяющий вставить входящее или плавающее изображение. Если изображение является метафайлом EMF или WMF, оно будет вставлено в документ в формате метафайла. Все остальные изображения будут храниться в формате PNG. The InsertImage Метод может использовать изображения из разных источников:

  • из файла или URL проходя мимо String параметр InsertImage
  • из ручья, проходя мимо Stream параметр InsertImage
  • от объекта изображения путем прохождения параметра изображения InsertImage
  • из байтового массива путем пропускания параметра байтового массива InsertImage

Для каждого из них InsertImage Есть дополнительные перегрузки, которые позволяют вставить изображение со следующими опциями:

  • наклонные или плавающие в определенном положении, например, InsertImage
  • Процентная шкала или пользовательский размер, например, InsertImageБолее того, InsertImage Способ возвращает Shape объект, который был только что создан и вставлен, чтобы вы могли дополнительно изменять свойства формы

Как вставить встроенное изображение

Передайте одну строку, представляющую файл, который содержит изображение для InsertImage вставить изображение в документ в виде встроенной графики

Следующий пример кода показывает, как вставить встроенное изображение в положение курсора в документ:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertImage(dataDir + "Watermark.png");
dataDir = dataDir + "DocumentBuilderInsertInlineImage_out.doc";
doc.Save(dataDir);

Как вставить плавающее изображение

Следующий пример кода показывает, как вставить плавающее изображение из файла или URL в определенном положении и размере:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertImage(dataDir + "Watermark.png",
RelativeHorizontalPosition.Margin,
100,
RelativeVerticalPosition.Margin,
100,
200,
100,
WrapType.Square);
dataDir = dataDir + "DocumentBuilderInsertFloatingImage_out.doc";
doc.Save(dataDir);

Как извлечь изображения из документа

Все изображения хранятся внутри Shape узлы в Document. Чтобы извлечь из документа все изображения или изображения определенного типа, выполните следующие действия:

  • Используйте GetChildNodes Способ выбрать все Shape Узлы.
  • Итерировать через результирующие коллекции узлов.
  • Проверьте. HasImage Булева собственность.
  • Извлекать данные изображения с помощью ImageData собственность.
  • Сохранить данные изображения в файл.

Следующий пример кода показывает, как извлечь изображения из документа и сохранить их в виде файлов:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithImages();
Document doc = new Document(dataDir + "Image.SampleImages.doc");
NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
int imageIndex = 0;
foreach (Shape shape in shapes)
{
if (shape.HasImage)
{
string imageFileName = string.Format(
"Image.ExportImages.{0}_out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
shape.ImageData.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-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithImages();
// Create a blank documenet.
Document doc = new Document();
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.FirstSection, 1, HeaderFooterType.FooterPrimary);
for (int i = 1; i < numPages; i++)
{
// Clone the first section and add it into the end of the document.
Section cloneSection = (Section)doc.FirstSection.Clone(false);
cloneSection.PageSetup.SectionStart = SectionStart.NewPage;
doc.AppendChild(cloneSection);
// Insert the barcode and other information into the footer of the section.
InsertBarcodeIntoFooter(builder, cloneSection, i, HeaderFooterType.FooterPrimary);
}
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-.NET
private static void InsertBarcodeIntoFooter(DocumentBuilder builder, Section section, int pageId, HeaderFooterType footerType)
{
// Move to the footer type in the specific section.
builder.MoveToSection(section.Document.IndexOf(section));
builder.MoveToHeaderFooter(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.InsertImage(System.Drawing.Image.FromFile( RunExamples.GetDataDir_WorkingWithImages() + "Barcode1.png"));
builder.Writeln();
builder.Write("1234567890");
builder.InsertField("PAGE");
// Create a right aligned tab at the right margin.
double tabPos = section.PageSetup.PageWidth - section.PageSetup.RightMargin - section.PageSetup.LeftMargin;
builder.CurrentParagraph.ParagraphFormat.TabStops.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");
}

Соотношение сторон изображения

Соотношение сторон геометрической формы - это отношение ее размеров в разных размерах. Вы можете заблокировать соотношение сторон изображения с помощью AspectRatioLocked. Значение по умолчанию отношения сторон формы зависит от ShapeType. Это true для ShapeType.Image и false для других типов форм.

Следующий пример кода показывает, как работать с соотношением сторон:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
var shape = builder.InsertImage(dataDir + "Test.png");
shape.AspectRatioLocked = false;
dataDir = dataDir + "Shape_AspectRatioLocked_out.doc";
// Save the document to disk.
doc.Save(dataDir);

Как получить реальные границы формы в точках

Если вы хотите, чтобы фактическая ограничительная коробка формы отображалась на странице, вы можете достичь этого, используя BoundsInPoints собственность.

Следующий пример кода показывает, как использовать это свойство:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
var shape = builder.InsertImage(dataDir + "Test.png");
shape.AspectRatioLocked = false;
Console.Write("\nGets the actual bounds of the shape in points.");
Console.WriteLine(shape.GetShapeRenderer().BoundsInPoints);

Изображения Crop

Обрезка изображения обычно относится к удалению нежелательных внешних частей изображения, чтобы помочь улучшить обрамление. Он также используется для удаления некоторых частей изображения, чтобы увеличить фокус на определенной области.

Следующий пример кода показывает, как достичь этого с помощью Aspose.Words API:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithImages();
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-.NET
public static void CropImage(string inPath, string outPath, int left, int top,int width, int height)
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Image img = Image.FromFile(inPath);
int effectiveWidth = img.Width - width;
int effectiveHeight = img.Height - height;
Shape croppedImage = builder.InsertImage(img,
ConvertUtil.PixelToPoint(img.Width - effectiveWidth),
ConvertUtil.PixelToPoint(img.Height - effectiveHeight));
double widthRatio = croppedImage.Width / ConvertUtil.PixelToPoint(img.Width);
double heightRatio = croppedImage.Height / ConvertUtil.PixelToPoint(img.Height);
if (widthRatio< 1)
croppedImage.ImageData.CropRight = 1 - widthRatio;
if (heightRatio< 1)
croppedImage.ImageData.CropBottom = 1 - heightRatio;
float leftToWidth = (float)left / img.Width;
float topToHeight = (float)top / img.Height;
croppedImage.ImageData.CropLeft = leftToWidth;
croppedImage.ImageData.CropRight = croppedImage.ImageData.CropRight - leftToWidth;
croppedImage.ImageData.CropTop = topToHeight;
croppedImage.ImageData.CropBottom = croppedImage.ImageData.CropBottom - 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-.NET
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
RtfSaveOptions saveOpts = new RtfSaveOptions();
saveOpts.SaveImagesAsWmf = true;
doc.Save(dataDir + "output.rtf", saveOpts);