Pictures

  • 7 minutes to read
NOTE

Refer to the Shapes article for information on new pictures and shapes.

The RichEditDocumentServer supports the following graphic types:

  • Bitmap (*.bmp, *.dib)
  • JPEG File Interchange Format (*.jpg, *.jpeg)
  • Portable Network Graphics (*.png)
  • Graphics Interchange Format (*.gif)
  • Tagged Image Format (*.tif, *.tiff)
  • Microsoft Enhanced Metafile (*.emf)
  • Windows Metafile (*.wmf)

Create an Image

All images in the document are contained in two collections: DocumentImageCollection (accessible by the SubDocument.Images property) and ShapeCollection (accessible by the SubDocument.Shapes property).

Call the DocumentImageCollection.Append or DocumentImageCollection.Insert method to place an inline image in the document. The resulting object is also added to the ShapeCollection.

NOTE

When you work with documents created in a Microsoft Word version earlier than 2007, its inline pictures are stored in the DocumentImageCollection only.

This example illustrates how to insert inline pictures in a rich text document. The image can be obtained from a file, from a stream or from a URI.

using System.IO;
using System.Reflection;
using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.API.Native;
RichEditDocumentServer server = new RichEditDocumentServer();

server.LoadDocument("Texts\\InlinePictures.rtf", DocumentFormat.Rtf);
Document doc = server.Document;

// Insert an image from a file.
DocumentRange rangeFound = doc.FindAll("Visual Studio Magazine", SearchOptions.CaseSensitive)[0];
DocumentPosition pos = doc.Paragraphs[doc.Paragraphs.Get(rangeFound.End).Index + 2].Range.Start;
doc.Images.Insert(pos, DocumentImageSource.FromFile("Pictures\\ReadersChoice.png"));

// Insert an image from a stream.
pos = doc.Paragraphs[4].Range.Start;
string imageToInsert = "information.png";
Assembly a = Assembly.GetExecutingAssembly();
Stream imageStream = a.GetManifestResourceStream("InlinePictures.Resources." + imageToInsert);
doc.Images.Insert(pos, DocumentImageSource.FromStream(imageStream));

// Insert an image using its URI.
string imageUri = "http://i.gyazo.com/798a2ed48a3535c6c8add0ea7a4fc4e6.png";
SubDocument docHeader = doc.Sections[0].BeginUpdateHeader();
docHeader.Images.Append(DocumentImageSource.FromUri(imageUri, server));
doc.Sections[0].EndUpdateHeader(docHeader);


// Insert a barcode.
DevExpress.BarCodes.BarCode barCode = new DevExpress.BarCodes.BarCode();
barCode.Symbology = DevExpress.BarCodes.Symbology.QRCode;
barCode.CodeText = "http://www.devexpress.com";
barCode.CodeBinaryData = System.Text.Encoding.Default.GetBytes(barCode.CodeText);
barCode.Module = 0.5;
SubDocument docFooter = doc.Sections[0].BeginUpdateFooter();
docFooter.Images.Append(barCode.BarCodeImage);
doc.Sections[0].EndUpdateFooter(docFooter);

Resize an Image

The following properties allow you to resize an inline image:

API

Description

DocumentImage.ScaleX

Gets or sets the X-axis scale factor.

DocumentImage.ScaleY

Gets or sets the Y-axis scale factor.

DocumentImage.Size

Specifies the picture's size in current measurement units (specified by the Document.Unit property).

The following example examines all images in the document. If the width of an image exceeds 50 millimeters, the image is scaled proportionally to half its size.

Document document = server.Document;
document.LoadDocument("Documents\\Grimm.docx", DocumentFormat.OpenXml);
ReadOnlyDocumentImageCollection images = document.Images;
// If the width of an image exceeds 50 millimeters, 
// the image is scaled proportionally to half its size.
for (int i = 0; i < images.Count; i++)
{
    if (images[i].Size.Width > DevExpress.Office.Utils.Units.MillimetersToDocumentsF(50))
    {
        images[i].ScaleX /= 2;
        images[i].ScaleY /= 2;
    }
}

Obtain Image Information

The DocumentImage.Image property enables you to get information on image size, resolution and color depth. The returned OfficeImage object can be used to get a native .NET Image (the OfficeImage.NativeImage property) or to get image data in a different format (the OfficeImage.GetImageBytes method).

The code sample below retrieves all images in the document and saves them as separate files.

The code sample below retrieves all images in the specific document range and exports them in the PNG format.

Document document = server.Document;
document.LoadDocument("Documents\\MovieRentals.docx", DocumentFormat.OpenXml);
DocumentRange myRange = document.CreateRange(0, 100);

// Obtain all images im the specific range:
ReadOnlyDocumentImageCollection images = document.Images.Get(myRange);

// Export the retrieved images as png files:
if (images.Count > 0)
{
    DevExpress.Office.Utils.OfficeImage myImage = images[0].Image;
    System.Drawing.Image image = myImage.NativeImage;
    string imageName = String.Format("Image_at_pos_{0}.png", images[0].Range.Start.ToInt());
    image.Save(imageName);
    System.Diagnostics.Process.Start("explorer.exe", "/select," + imageName);
}
TIP

Use the ReadOnlyDocumentImageCollection.Get method to get images from the specified range.

Delete an Image

Clear the range occupied by the image to delete this image from the document. The DocumentImage.Range property returns the related range.

DocumentRange imageRange = richEditDocumentServer1.Document.Images[0].Range;
richEditDocumentServer1.Document.Delete(imageRange);

Export Specifics

RTF

Use the RtfDocumentExporterCompatibilityOptions.DuplicateObjectAsMetafile property to specify whether to save inline pictures in the native format and as metafiles.

HTML

Handle the RichEditDocumentServer.BeforeExport event and specify the HtmlDocumentExporterOptions.UriExportType and IExporterOptions.TargetUri properties to specify a location for storing images as external files.

Create custom IUriProvider interface implementation and specify it instead of the default URI provider in the SubDocument.GetHtmlText method to create custom css and image URIs.

This example demonstrates how to use the DocumentImage.Uri property to set the image's src attribute when a document is saved in HTML format. You can switch on the HtmlDocumentExporterOptions.EmbedImages option to observe that the custom URI provider is idle for embedded images.

NOTE

The complete sample project How to retain the original image URI in an HTML document is available in the DevExpress Examples repository.

using DevExpress.Office.Services;
using DevExpress.XtraRichEdit.API.Native;
using DevExpress.XtraRichEdit.Export;
using System;
// ...
        private void richEditControl1_DocumentLoaded(object sender, EventArgs e)
        {
            IUriProviderService service = richEditControl1.GetService<IUriProviderService>();
            if (service != null) {
                service.RegisterProvider(new CustomUriProvider());
            }
        }
        private void richEditControl1_ContentChanged(object sender, EventArgs e)
        {
            ReloadHtml();
        }

        private void ReloadHtml()
        {
            HtmlDocumentExporterOptions exportOptions = new HtmlDocumentExporterOptions();
            exportOptions.EmbedImages = embedImagesCheck.Checked;
            string sText = richEditControl1.Document.GetHtmlText(richEditControl1.Document.Range, new CustomUriProvider(), exportOptions);
            memoEdit1.Text = sText;
        }

The Document.HtmlText property uses a special URI provider (the DataStringUriProvider), which converts an image to a base64-encoded representation with the "data:" prefix. If you use the Document.HtmlText property to obtain the HTML content, all images are embedded in the page.