English

How To: Add a JPEG image to ArcMap using VBA and ArcObjects

Summary

This article shows how to add a JPEG image to ArcMap using IRasterLayer::CreateFromDataset.

Procedure

  1. Start ArcMap.
  2. On your system, locate a JPEG image file that you would like to load into ArcMap as a raster layer.
  3. Open the Visual Basic Editor.

    In ArcMap, select Tools > Macros > Visual Basic Editor.

  4. In the Project Explorer window, expand the Project folder and select ThisDocument. Right-click and select View Code.
    [O-Image] Visual Basic Project  Explorer
    Note:
    Code in ThisDocument module will only run in the current map document. To store the code in all your map documents, open the Normal.mxt ThisDocument code module.

  5. Copy the following into the code module.

    Code:
    Public Sub AddRasterLayer()

    Dim pMxDocument As IMxDocument
    Dim pMap As IMap
    Dim pLayer As IRasterLayer
    Dim pWF As IWorkspaceFactory
    Dim pWs As IWorkspace
    Dim pFW As IRasterWorkspace
    Dim pDataset As IDataset
    Dim pRDataset As IRasterDataset

    Set pWF = New RasterWorkspaceFactory

    ' Enter path to the directory that contains the image file
    Set pWs = pWF.OpenFromFile("C:\Images", 0)

    ' QI
    Set pFW = pWs
    ' Enter Name of the image file
    Set pRDataset = pFW.OpenRasterDataset("seb1.jpg")

    ' Create the dataset
    Dim pRLayer As IRasterLayer
    Set pRLayer = New RasterLayer
    pRLayer.CreateFromDataset pRDataset

    'Add the raster layer to the map
    Set pMxDocument = ThisDocument
    Set pMap = pMxDocument.FocusMap
    pMxDocument.AddLayer pRLayer

    End Sub

  6. In the VBA code, update the string in the OpenFromFile statement to reflect the folder in which the JPEG file is located. Update the string in the OpenRasterDataset statement to reflect the JPEG file name.
  7. Close the Visual Basic Editor.
  8. Run the code.

    A. Click Tools > Macros > Macros to display the Macros dialog box.
    B. Select a macro and click Run.