與圖像合作

Aspose.Words 能讓使用者以非常靈活的方式與圖像處理。 在本文中,你只能探索與圖像工作的一些可能性。

如何插入圖像

DocumentBuilder 提供 InsertImage 方法的幾個重載,讓您可以插入內嵌或浮動式圖表。 如果圖片是 EMF 或 WMF 元檔案,它將會以元檔案格式插入到該文件中。 所有其他圖像將以PNG格式儲存。 InsertImage這個方法可從不同的來源使用圖像:

  • 从文件或 URL 通过传递 String 参数 InsertImage
  • 从流中通过传递一个 Stream 参数 InsertImage
  • 透過傳入一個 Image 參數來獲取 Image 物件 InsertImage “-透過傳遞字節陣列參數來從字節陣列中導出” 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);

如何從文件中提取圖像

所有圖像都儲存在 Shape 個節點中,以 Document 的方式儲存。 從文件中提取所有圖片或特定類型的圖片,請按照以下步驟操作:

  • 使用 GetChildNodes 方法選取所有 Shape 節點。
  • 迭代 resulting node 集合。
  • 檢查 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文件的所有或特定頁面上,新增相同的或不同的條碼。 沒有方法可以直接在文件的所有頁面上加入條碼,但您可以利用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。 它為 trueShapeType.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);

如何獲得形狀的實際邊界在點 {#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提供在將DOCX轉為RTF的同時,將文件中的所有可用圖片儲存到WMF格式的功能。

接下來的程式碼範例示範了如何以 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);