处理图像

Aspose.Words 允许用户以非常灵活的方式处理图像。在本文中,您只能探索处理图像的一些可能性。

如何插入图像

DocumentBuilder 提供了 InsertImage 方法的多个重载,允许您插入内联或浮动图像。如果图像是 EMF 或 WMF 图元文件,它将以图元文件格式插入到文档中。所有其他图像都将以 PNG 格式存储。 InsertImage 方法可以使用来自不同来源的图像:

  • 通过传递 String 参数 InsertImage 从文件或 URL
  • 通过传递 Stream 参数 InsertImage 从流中
  • 通过传递 Image 参数 InsertImage 从 Image 对象
  • 通过传递字节数组参数 InsertImage 从字节数组中获取

对于每个 InsertImage 方法,还有更多重载,允许您使用以下选项插入图像:

  • 内联或浮动在特定位置,例如 InsertImage
  • 百分比比例或自定义尺寸,例如 InsertImage;此外,InsertImage 方法返回刚刚创建和插入的 Shape 对象,以便您可以进一步修改 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);

如何从文档 {#how-to-extract-images-from-a-document} 中提取图像

所有图像都存储在 Document 中的 Shape 节点内。要从文档中提取所有图像或具有特定类型的图像,请按照下列步骤操作:

  • 使用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++;
}
}

如何在每个文档页 {#how-to-insert-barcode-on-each-documen-page} 上插入条形码

此示例演示如何在 Word 文档的所有或特定页面上添加相同或不同的条形码。没有直接的方法可以在文档的所有页面上添加条形码,但您可以使用 MoveToSectionMoveToHeaderFooterInsertImage 方法移动到任何部分或页眉/页脚并插入条形码图像,如以下代码所示。

以下代码示例演示如何在文档的每一页上插入条形码图像:

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

锁定图像 {#lock-aspect-ratio-of-image} 的长宽比

几何形状的长宽比是其在不同维度上的大小之比。您可以使用 AspectRatioLocked 锁定图像的纵横比。形状纵横比的默认值取决于 ShapeType。对于 ShapeType.Image,它是 true;对于其他形状类型,它是 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);

如何获取点 {#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-.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);

裁剪图像

图像的裁剪通常是指去除图像中不需要的外部部分以帮助改善取景。它还用于删除图像的某些部分以增加对特定区域的关注。

以下代码示例展示了如何使用 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 的功能。

以下代码示例演示如何使用 RTF 保存选项将图像保存为 WMF:

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