Search code examples
c#autocad

I have to insert a logo in AutoCAD title block by using C#?


I have to insert a image in AutoCAD title block at particular insertion point with its width and height, so that I can use scale function to that template while using it. I used RasterImage but not getting the proper result.

please write a code for insert a image at particular point of modelspace in AutoCAD.


Solution

  • I replied to the same question in the Autodesk forum.

            static void InsertImage(Database db, string fileName, Point3d position, double width, double height)
        {
            string imgName = System.IO.Path.GetFileNameWithoutExtension(fileName);
            using (var tr = db.TransactionManager.StartTransaction())
            {
                var imgDictId = RasterImageDef.GetImageDictionary(db);
                if (imgDictId.IsNull)
                    imgDictId = RasterImageDef.CreateImageDictionary(db);
                var imgDict = (DBDictionary)tr.GetObject(imgDictId, OpenMode.ForRead);
                ObjectId imgDefId;
                RasterImageDef imgDef;
                if (imgDict.Contains(imgName))
                {
                    imgDefId = imgDict.GetAt(imgName);
                    imgDef = (RasterImageDef)tr.GetObject(imgDefId, OpenMode.ForRead);
                }
                else
                {
                    imgDef = new RasterImageDef();
                    imgDef.SourceFileName = fileName;
                    imgDef.Load();
                    tr.GetObject(imgDictId, OpenMode.ForWrite);
                    imgDefId = imgDict.SetAt(imgName, imgDef);
                    tr.AddNewlyCreatedDBObject(imgDef, true);
                }
    
                var modelSpace = (BlockTableRecord)tr.GetObject(
                    SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite);
    
                var raster = new RasterImage();
                raster.ImageDefId = imgDefId;
                var coordSystem = new CoordinateSystem3d(
                    position, Vector3d.XAxis * width, Vector3d.YAxis * height);
                raster.Orientation = coordSystem;
                modelSpace.AppendEntity(raster);
                tr.AddNewlyCreatedDBObject(raster, true);
                RasterImage.EnableReactors(true);
                raster.AssociateRasterDef(imgDef);
                tr.Commit();
            }
        }