Praca z obrazami

Aspose.Words pozwala użytkownikom pracować z obrazami w bardzo elastyczny sposób. W tym artykule możesz poznać tylko niektóre możliwości pracy z obrazami.

Jak wstawić obraz

DocumentBuilder zapewnia kilka przeciążeń metody InsertImage, które umożliwiają wstawienie obrazu wbudowanego lub pływającego. Jeśli obraz jest metaplikiem EMF lub WMF, zostanie wstawiony do dokumentu w formacie metapliku. Wszystkie pozostałe obrazy będą przechowywane w formacie PNG. Metoda InsertImage może wykorzystywać obrazy z różnych źródeł:

  • Z pliku lub URL, przekazując parametr String InsertImage
  • Ze strumienia poprzez przekazanie parametru Stream InsertImage
  • Z obiektu Image poprzez przekazanie parametru Image InsertImage
  • Z tablicy bajtów poprzez przekazanie parametru tablicy bajtów InsertImage

Dla każdej z metod InsertImage istnieją dalsze przeciążenia, które umożliwiają wstawienie obrazu z następującymi opcjami:

  • Inline lub pływający w określonej pozycji, na przykład InsertImage
  • Skala procentowa lub rozmiar niestandardowy, np. InsertImage; ponadto metoda InsertImage zwraca obiekt Shape, który właśnie został utworzony i wstawiony, dzięki czemu można dalej modyfikować właściwości kształtu

Jak wstawić obraz śródliniowy

Przekaż pojedynczy ciąg reprezentujący plik zawierający obraz do InsertImage, aby wstawić obraz do dokumentu jako grafikę wstawioną

Poniższy przykład kodu pokazuje, jak wstawić obraz osadzony w pozycji kursora do dokumentu:

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

Jak wstawić pływający obraz

Poniższy przykład kodu pokazuje, jak wstawić pływający obraz z pliku lub URL w określonej pozycji i rozmiarze:

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

Jak wyodrębnić obrazy z dokumentu

Wszystkie obrazy są przechowywane w węzłach Shape w formacie Document. Aby wyodrębnić z dokumentu wszystkie obrazy lub obrazy określonego typu, wykonaj następujące kroki:

  • Użyj metody GetChildNodes, aby wybrać wszystkie węzły Shape.
  • Iteruj po wynikowych kolekcjach węzłów.
  • Sprawdź właściwość logiczną HasImage.
  • Wyodrębnij dane obrazu za pomocą właściwości ImageData.
  • Zapisz dane obrazu w pliku.

Poniższy przykład kodu pokazuje, jak wyodrębnić obrazy z dokumentu i zapisać je jako pliki:

// 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++;
}
}

Jak wstawić kod kreskowy na każdej stronie dokumentu

Ten przykład pokazuje, jak dodać te same lub różne kody kreskowe na wszystkich lub określonych stronach dokumentu programu Word. Nie ma bezpośredniego sposobu dodawania kodów kreskowych na wszystkich stronach dokumentu, ale można użyć metod MoveToSection, MoveToHeaderFooter i InsertImage, aby przejść do dowolnej sekcji lub nagłówka/stopki i wstawić obrazy kodów kreskowych, jak widać w poniższym kodzie.

Poniższy przykład kodu pokazuje, jak wstawić obraz kodu kreskowego na każdej stronie dokumentu:

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

Zablokuj współczynnik proporcji obrazu

Proporcje kształtu geometrycznego to stosunek jego rozmiarów w różnych wymiarach. Możesz zablokować proporcje obrazu za pomocą AspectRatioLocked. Domyślna wartość współczynnika proporcji kształtu zależy od ShapeType. Jest to true dla ShapeType.Image i false dla innych typów kształtów.

Poniższy przykład kodu pokazuje, jak pracować ze współczynnikiem proporcji:

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

Jak uzyskać rzeczywiste granice kształtu w punktach

Jeśli chcesz, aby rzeczywista ramka ograniczająca kształt była renderowana na stronie, możesz to osiągnąć za pomocą właściwości BoundsInPoints.

Poniższy przykład kodu pokazuje, jak używać tej właściwości:

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

Przytnij obrazy

Kadrowanie obrazu zwykle oznacza usunięcie niepożądanych zewnętrznych części obrazu w celu poprawy kadrowania. Służy również do usuwania niektórych części obrazu w celu zwiększenia ostrości na określonym obszarze.

Poniższy przykład kodu pokazuje, jak to osiągnąć za pomocą 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));
}

Zapisz obrazy jako WMF

Aspose.Words zapewnia funkcję zapisywania wszystkich dostępnych obrazów w dokumencie do formatu WMF podczas konwersji DOCX do RTF.

Poniższy przykład kodu pokazuje, jak zapisywać obrazy w formacie WMF z opcjami zapisywania w formacie 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);