Inserting Images Help

Inserting Images Help

lvthunder
Advocate Advocate
1,309 Views
7 Replies
Message 1 of 8

Inserting Images Help

lvthunder
Advocate
Advocate

I'm using this code to insert images, but I'm getting an error.

    Public Function Add_Raster(ByRef ThisDoc As Document, ByVal RasterFile As String, ByVal InsPoint As Point3d, ByVal Scale As Double, ByRef NumInserted As Integer) As RasterImage

        Dim RasterEnt As RasterImage, RasterDef As RasterImageDef
        Dim ImageDicID, ImageDefID As ObjectId, ImageDic As DBDictionary
        Dim Matrix As Geometry.Matrix3d
        Dim btr As BlockTableRecord
        Dim RasterName As String = ""

        RasterName = RasterFile.Substring(RasterFile.LastIndexOf("\") + 1)
        RasterName = RasterName.Substring(0, RasterName.IndexOf("."))

        Add_Raster = Nothing
        If ThisDoc Is Nothing Then Exit Function

        Try

            Using Trans As Transaction = ThisDoc.TransactionManager.StartTransaction()

                RasterEnt = New RasterImage
                RasterEnt.Dispose() ' force loading of RasterImage.dbx module (needed for 2009 and earlier)

                RasterDef = New RasterImageDef
                RasterDef.SourceFileName = RasterFile
                RasterDef.ActiveFileName = RasterFile
                RasterDef.Load()

                ImageDicID = RasterImageDef.GetImageDictionary(ThisDoc.Database)
                If ImageDicID.IsNull Then
                    RasterImageDef.CreateImageDictionary(ThisDoc.Database)
                    ImageDicID = RasterImageDef.GetImageDictionary(ThisDoc.Database)
                End If
                If ImageDicID.IsNull Then
                    MsgBox("Could not create image dictionary", MsgBoxStyle.Critical, "Failed")
                    'Exit Try
                End If
                ImageDic = Trans.GetObject(ImageDicID, OpenMode.ForWrite)
                If ImageDic Is Nothing Then
                    MsgBox("Could not open image dictionary", MsgBoxStyle.Critical, "Failed")
                Else
                    If ImageDic.Contains(RasterName) Then
                        MsgBox("That image name is already in use", MsgBoxStyle.Critical, "Failed")
                    Else
                        ImageDic.UpgradeOpen()
                        ImageDefID = ImageDic.SetAt(RasterName, RasterDef)
                        Trans.AddNewlyCreatedDBObject(RasterDef, True)
                        RasterEnt = New RasterImage
                        RasterEnt.SetDatabaseDefaults(ThisDoc.Database)
                        RasterEnt.ColorIndex = 256
                        RasterEnt.Linetype = "ByLayer"
                        RasterEnt.LineWeight = LineWeight.ByLayer
                        'If IsSTB Then RasterEnt.PlotStyleName = "ByLayer"
                        Matrix = New Geometry.Matrix3d
                        Matrix = Geometry.Matrix3d.Scaling(Scale / RasterDef.Size.X, New Point3d(0, 0, 0))
                        RasterEnt.TransformBy(Matrix)
                        Matrix = Geometry.Matrix3d.Displacement(New Vector3d(InsPoint.X, InsPoint.Y, InsPoint.Z))
                        RasterEnt.TransformBy(Matrix)
                        RasterEnt.ImageDefId = ImageDefID
                        btr = Trans.GetObject(ThisDoc.Database.CurrentSpaceId, OpenMode.ForWrite)
                        btr.AppendEntity(RasterEnt)
                        Trans.AddNewlyCreatedDBObject(RasterEnt, True)
                        Trans.Commit()
                        NumInserted = NumInserted + 1
                    End If
                End If

            End Using

            Add_Raster = RasterEnt

        Catch ex As Autodesk.AutoCAD.Runtime.Exception

            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.ToString & vbCr & ex.Message)

        End Try

    End Function

 and this to call the function

    <CommandMethod("img")> _
    Public Sub img()
        Dim myDB2 As Document = ApplicationServices.Application.DocumentManager.MdiActiveDocument
        Dim Point As New Point3d(0, 0, 0)
        Add_Raster(myDB2, "c:\test.jpg", Point, 0, 1)
    End Sub

 I get the following error:

 

Autodesk.AutoCAD.Runtime.Exception: eInvalidInput

at Autodesk.AutoCAD.DabaseServices.Entity.TransformBy(Matrix3d transform)

at Kin.CommonFunctions.Add_Raster(Document& ThisDoc, String RasterFile, Point3d InsPoint, Double Scale, Int32& NumInserted) in C:\{path to vb file}: line 406 eInvalidInput

0 Likes
1,310 Views
7 Replies
Replies (7)
Message 2 of 8

Virupaksha_aithal
Autodesk Support
Autodesk Support

Looks like you are passing scale as 0.  Pass a valid value as scale to your “Add_Raster” function.  

 

Virupaksha Aithal

Autodesk developer Network



Virupaksha Aithal KM
Developer Technical Services
Autodesk Developer Network

Message 3 of 8

lvthunder
Advocate
Advocate

Ok that worked great, but that was just me testing the function.  In my program I'm taking a folder full of images and creating a new drawing from a template and inserting the image.  Here is that part.

 

<CommandMethod("Kin")> _
    Public Sub Kin() ' This method can have any name
        Options()
        Dim strTemplatePath As String = filepath & "template.dwt"
        filename = IO.Directory.GetFiles(filepath, "*.jpg")
        For i As Integer = 0 To filename.Length
            id = i
            Using acCurDb As New Database(True, False)
                Using tr As Transaction = acCurDb.TransactionManager.StartTransaction()
                    ' Lock the drawing in the editor.
                    Dim acDocMgr As DocumentCollection = ApplicationServices.Application.DocumentManager
                    AcDoc = acDocMgr.Add(strTemplatePath)
                    Using lock As DocumentLock = AcDoc.LockDocument
                        ' Write out new Drawing File.
                        plan()
                        AcDoc.Database.SaveAs(fileoutpath & filename(i) & ".dwg", DwgVersion.Current, DwgVersion.Current, acCurDb.SecurityParameters)
                    End Using
                End Using
            End Using
            AcDoc.CloseAndDiscard()
        Next i
    End Sub

 and it is giving me this

 

Autodesk.AutoCAD.Runtime.Exception: eWrongDatabse

at AutodeskAutoCAD.DatabaseServices.Entity.set_Linetype(String newValue)

at Kin.CommonFunctions.Add_Raster(Document& ThisDoc, String RasterFile, Point3d InsPoint, Double Scale, Int32& NumInserted) in c:\{folder path}:line 401

eWrongDatabase

0 Likes
Message 4 of 8

lvthunder
Advocate
Advocate

Doesn't anyone have any ideas?

0 Likes
Message 5 of 8

norman.yuan
Mentor
Mentor

Well, the code in your second post does not show where the  Kin.CommonFunctions.Add_Raster() method is called (I guess it is inside the plan() procedure call. Since  Kin.CommonFunctions.Add_Raster() requires a few parameters passed in, while the plan() procedure does not take any, it is a typical bad practice of writing code: it is very easy to pass wrong parameters to the  Kin.CommonFunctions.Add_Raster() method. But not seeing the code, I cannot say more on this.

 

Also, why do you create a new Database and start a transaction with it before looping through each file based a file name array? It is completely unnecessary. It is likely the error was due to you passing this database instead of the database of newly added drawing to the method.

 

Finally, since you are opening a searies of new drawings and do something (inserting image?) and then closing them one by one, the command method for doing it should be set with CommandFlags.Session.

Norman Yuan

Drive CAD With Code

EESignature

0 Likes
Message 6 of 8

lvthunder
Advocate
Advocate

Sorry the plan method is just used to help me organize the different parts of the program.  Here is the code.

    Private Sub plan()
        Dim point As New Point3d(0, 0, 0.0)
        Add_Raster(AcDoc, filename(id), point, 1, 1)
    End Sub

 As to why I'm creating a new database and start a transaction with it before looping...  Because I'm new to this and that's the way it worked when I made a program that read an Excel sheet and inserted a bunch of blocks.

 

Last time I messed with CommandFlags.Session I just got a bunch of errors and since it worked when I was doing the blocks I just left it alone.

0 Likes
Message 7 of 8

kstate92
Collaborator
Collaborator

You've gotten farther than I have.  I have the same basic code I found on theswap.org during a search, but I can't get past this part:

 

ImageDicID = RasterImageDef.GetImageDictionary(ThisDoc.Database)
    If ImageDicID.IsNull Then
        RasterImageDef.CreateImageDictionary(ThisDoc.Database)
        ImageDicID = RasterImageDef.GetImageDictionary(ThisDoc.Database)

 

ImageDicID is null after the first GetImageDictionary line (which I expected as I'm creating a new empty drawing solely for inserting a tiff image), but it crashes on the CreateImageDictionary line, whereas achieving the same goal in VBA just uses this:


            Set RasterObj = MyAcad.ActiveDocument.ModelSpace.AddRaster _
                (strTifFile, dblInsertPoint, dblScaleFactor, dblRotationAngle)

KState92
Inventor Professional 2020
AutoCAD Mechanical 2022.0.1
Windows 10 Pro 64 bit - 1903
Core i7-8700 32 GB Ram
Quadro P2000
0 Likes
Message 8 of 8

kstate92
Collaborator
Collaborator

Adding ThisDoc.LockDocument() prior to the transaction seems to have eliminated my image insert error.  Now onto scaling up my tiny inserted tiff image...

KState92
Inventor Professional 2020
AutoCAD Mechanical 2022.0.1
Windows 10 Pro 64 bit - 1903
Core i7-8700 32 GB Ram
Quadro P2000
0 Likes