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

Aspose.Words позволява на потребителите да работят с изображения по много гъвкав начин. В тази статия можете да разгледате само някои от възможностите за работа с изображения.

Как да въведете изображение

DocumentBuilder осигурява няколко претоварване на InsertImage метод, който ви позволява да вмъкнете в линия или плаващо изображение. Ако изображението е метафайл EMF или WMF, то ще бъде вмъкнато в документа във формат metafile. Всички останали изображения ще се съхраняват във формат PNG. На InsertImage метод може да използва изображения от различни източници:

  • От файл или URL чрез преминаване на String параметър InsertImage
  • От поток преминавайки Stream параметър InsertImage
  • От обект на изображение чрез преминаване на параметър на изображението InsertImage
  • От байт масив чрез преминаване на параметър байт масив InsertImage

За всяка от InsertImage методи, има допълнителни претоварване, които ви позволяват да въведете изображение със следните опции:

  • Inline или плаващи в определена позиция, например, InsertImage
  • Процент мащаб или потребителски размер, например, InsertImage; освен това, InsertImage метод връща a 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");
}

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

Житните изображения

Изрязването на изображение обикновено се отнася до премахването на нежеланите външни части на изображението, за да се подобри рамката. Използва се и за премахване на някои части от изображението за увеличаване на фокуса върху определена област.

Следният пример за код показва как да се постигне това използване 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);