Example #1
0
        /// <summary>
        ///     Gets the raster image def.
        /// </summary>
        /// <param name="db">The db.</param>
        /// <param name="trans">The trans.</param>
        /// <param name="rasterImageName">Name of the raster image.</param>
        /// <returns></returns>
        public static ObjectId GetRasterImageDef(Database db, Transaction trans, string rasterImageName)
        {
            PGA.MessengerManager.MessengerManager.AddLog("Start GetRasterImageDef");
            var rasterImageDefId = ObjectId.Null;

            // Get the Image Dictionary
            var imageDictionaryId = RasterImageDef.GetImageDictionary(db);

            if (imageDictionaryId == ObjectId.Null)
            {
                // No images defined?
                return(rasterImageDefId);
            }

            var imageDictionary = (DBDictionary)trans.GetObject(imageDictionaryId, OpenMode.ForRead);

            if (imageDictionary.Count.Equals(0))
            {
                // No images defined?
                return(rasterImageDefId);
            }

            foreach (DictionaryEntry imageDictionaryEntry in imageDictionary)
            {
                var imageName = imageDictionaryEntry.Key as string;
                if (rasterImageName.ToUpper() == imageName.ToUpper())
                {
                    rasterImageDefId = (ObjectId)imageDictionaryEntry.Value;
                    break;
                }
            }
            PGA.MessengerManager.MessengerManager.AddLog("End GetRasterImageDef");
            return(rasterImageDefId);
        }
Example #2
0
        /// <summary>
        /// Actualizamos la ruta de las imagenes del tablero
        /// </summary>
        /// <param name="tr">La transacción activa.</param>
        /// <param name="doc">El documento a cargar.</param>
        /// <param name="tablero">El nombre del bloque.</param>
        public static void UpdatePath(this Transaction tr, Document doc, string tablero)
        {
            BlockTable blk = doc.Database.BlockTableId.GetObject(OpenMode.ForWrite) as BlockTable;

            if (blk.Has(tablero))
            {
                BlockTableRecord tabRec = blk[tablero].GetObject(OpenMode.ForRead) as BlockTableRecord;
                DBObject         obj;
                foreach (ObjectId objId in tabRec)
                {
                    obj = objId.GetObject(OpenMode.ForRead);
                    if (obj is RasterImage)
                    {
                        obj.UpgradeOpen();
                        RasterImage  img     = obj as RasterImage;
                        String       appData = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                        String       imgFile = Path.Combine(appData, "Autodesk", "ApplicationPlugins", "Tabalim.bundle", "contents", "img", "tableros", String.Format("{0}.BMP", tablero));
                        DBDictionary imgDic  = RasterImageDef.GetImageDictionary(doc.Database).GetObject(OpenMode.ForRead) as DBDictionary;
                        if (File.Exists(imgFile) && imgDic.Contains(tablero))
                        {
                            RasterImageDef imgDef = imgDic.GetAt(tablero).GetObject(OpenMode.ForWrite) as RasterImageDef;
                            if (imgDef.SourceFileName != imgFile)
                            {
                                imgDef.SourceFileName = imgFile;
                                imgDef.Load();
                                //img.UpgradeOpen();
                                //img.ImageDefId = imgDef.Id;
                                //img.AssociateRasterDef(imgDef);
                            }
                        }
                    }
                }
            }
        }
Example #3
0
        public static void FixRasterImagePath(this Database db, Transaction tr, string imageFolder)
        {
            var imageDictId = RasterImageDef.GetImageDictionary(db);

            if (!imageDictId.IsNull)
            {
                using (var imageDict = (DBDictionary)tr.GetObject(imageDictId, OpenMode.ForRead))
                {
                    foreach (var currentObject in imageDict)
                    {
                        using (var imageDef = (RasterImageDef)tr.GetObject(currentObject.Value, OpenMode.ForWrite))
                        {
                            if (string.IsNullOrEmpty(imageDef.ActiveFileName) || !File.Exists(imageDef.ActiveFileName))
                            {
                                var fileName = Path.Combine(imageFolder, Path.GetFileName(imageDef.SourceFileName));
                                Logger.Info("IMAGE: {0} => {1}", imageDef.SourceFileName, fileName);
                                if (File.Exists(fileName))
                                {
                                    imageDef.SourceFileName = fileName;
                                    imageDef.Load();
                                }
                                else if (tr.IsRasterImageUsed(imageDef))
                                {
                                    throw new ApplicationException("Raster image file '" + fileName + "' not found");
                                }
                            }
                        }
                    }
                }
            }
        }
 private static void AchtergrondCommand(TileConfig tileConfig)
 {
     using (var tr = Application.DocumentManager.CurrentDocument.TransactionManager.StartTransaction()) {
         var i = new GeomapImage();
         tr.GetObject(Application.DocumentManager.CurrentDocument.Database.CurrentSpaceId, OpenMode.ForWrite);
         var ri = RasterImageDef.GetImageDictionary(Application.DocumentManager.MdiActiveDocument.Database);
     }
 }
Example #5
0
        public bool removeImgDefByName()
        {
            DocumentLock doclock = null;

            try
            {
                Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                doclock = doc.LockDocument();

                Database db = HostApplicationServices.WorkingDatabase;
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;

                using (Transaction t = tm.StartTransaction())
                {
                    try
                    {
                        // open the dictionary
                        Autodesk.AutoCAD.DatabaseServices.ObjectId imgDictID = RasterImageDef.GetImageDictionary(db);
                        DBDictionary imgDict;
                        if (imgDictID.OldId == 0)
                        {
                            imgDictID = RasterImageDef.CreateImageDictionary(db);
                        }

                        imgDict = (DBDictionary)t.GetObject(imgDictID, OpenMode.ForWrite);

                        if (imgDict.Contains(ImgName))
                        {
                            ObjectId       rasterDefID = imgDict.GetAt(ImgName);
                            RasterImageDef rasterDef   = (RasterImageDef)t.GetObject(rasterDefID, OpenMode.ForWrite);

                            rasterDef.Erase();


                            imgDict.Remove(ImgName);
                        }
                        imgDict.Close();
                    }
                    catch (Autodesk.AutoCAD.Runtime.Exception eex)
                    { }
                    catch (System.Exception ex) { }
                    t.Commit();
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception eex)
            { return(false); }
            catch (System.Exception ex) { return(false); }
            finally
            {
                doclock.Dispose();
            }

            return(true);
        }
Example #6
0
        private static DBDictionary AddOrGetImageDictionary(Database database, Transaction transaction)
        {
            var imageDictionary = RasterImageDef.GetImageDictionary(database);

            if (imageDictionary.IsNull)
            {
                imageDictionary = RasterImageDef.CreateImageDictionary(database);
            }
            var imageDictionaryForRead = transaction.GetObject(imageDictionary, OpenMode.ForRead) as DBDictionary;

            return(imageDictionaryForRead);
        }
Example #7
0
        public static void DrawImg(Point3d location, string fileName, string layerName, double height, double width, short colour = 255, bool isClosed = true)
        {
            Document doc       = Application.DocumentManager.MdiActiveDocument;
            Database currentDB = doc.Database;

            CreateLayer(layerName, colour);
            string imageName = System.IO.Path.GetFileNameWithoutExtension(fileName);

            using (Transaction tr = currentDB.TransactionManager.StartTransaction())
            {
                RasterImageDef rasterImgDef;
                ObjectId       imgDefId;
                ObjectId       imageDictId = RasterImageDef.GetImageDictionary(currentDB);
                if (imageDictId.IsNull)
                {
                    imageDictId = RasterImageDef.CreateImageDictionary(currentDB);
                }
                DBDictionary imageDictionary = tr.GetObject(imageDictId, OpenMode.ForRead) as DBDictionary;
                if (imageDictionary.Contains(imageName))
                {
                    imgDefId     = imageDictionary.GetAt(imageName);
                    rasterImgDef = tr.GetObject(imageDictId, OpenMode.ForWrite) as RasterImageDef;
                }
                else
                {
                    RasterImageDef newRasterDef = new RasterImageDef();
                    newRasterDef.SourceFileName = fileName;
                    newRasterDef.Load();
                    imageDictionary.UpgradeOpen();
                    imageDictId = imageDictionary.SetAt(imageName, newRasterDef);
                    tr.AddNewlyCreatedDBObject(newRasterDef, true);
                    rasterImgDef = newRasterDef;
                }
                BlockTable       blockTable       = tr.GetObject(currentDB.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord blockTableRecord = tr.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                using (RasterImage rasterImg = new RasterImage())
                {
                    rasterImg.ImageDefId = imageDictId;
                    Vector3d           widthV     = new Vector3d(width, 0, 0);
                    Vector3d           heightV    = new Vector3d(0, height, 0);
                    CoordinateSystem3d coordinate = new CoordinateSystem3d(location, widthV, heightV);
                    rasterImg.Orientation = coordinate;
                    rasterImg.Rotation    = 0;
                    rasterImg.Layer       = layerName;
                    blockTableRecord.AppendEntity(rasterImg);
                    tr.AddNewlyCreatedDBObject(rasterImg, true);
                    RasterImage.EnableReactors(true);
                    rasterImg.AssociateRasterDef(rasterImgDef);
                }
                tr.Commit();
            }
        }
Example #8
0
        ///// <summary>
        ///// Inserts the raster image using TFW.
        ///// </summary>
        ///// <param name="db">The db.</param>
        ///// <param name="imageFileName">Name of the image file.</param>
        ///// <param name="layerName">Name of the layer.</param>
        ///// <param name="colorIndex">Index of the color.</param>
        ///// <returns></returns>
        //public static ObjectId InsertRasterImageUsingTfw(Database db, string imageFileName, string layerName, int colorIndex)
        //{
        //    // Note that this function references the Raster Studio API.
        //    // The API will not demand load. Raster Studio must be initialized in case it is not loaded at startup
        //    // Reference LoadRasterStudioApi

        //    // TODO: Expect that the trans should not be passed as the COM operation will commit the insert...

        //    PGA.MessengerManager.MessengerManager.AddLog("Start InsertRasterImageUsingTfw");
        //    ObjectId rasterId = new ObjectId();

        //    try
        //    {
        //        string imageFolder = System.IO.Path.GetDirectoryName(imageFileName);
        //        string worldFileName = String.Empty;
        //        worldFileName = System.IO.Path.GetFileNameWithoutExtension(imageFileName);
        //        worldFileName += ".tfw";
        //        worldFileName = System.IO.Path.Combine(imageFolder, worldFileName);

        //        // Verify image file exists
        //        if (!System.IO.File.Exists(imageFileName))
        //        {
        //            return rasterId;
        //        }

        //        // Verify world correlation file exists
        //        if (!System.IO.File.Exists(worldFileName))
        //        {
        //            return rasterId;
        //        }

        //        using (Transaction trans = db.TransactionManager.StartTransaction())
        //        {
        //            // Create new image object
        //            AecImageInsert imageInsert = new AecImageInsert();
        //            // Set image object to reference correlation file
        //            imageInsert.CorrelationSource = _aecImageInsertWorldFileCorrelationSource;
        //            // Insert a new image and get an Object Id back as integer (COM cannot return an ObjectId)
        //            IntPtr oidInteger = (IntPtr)imageInsert.Insert(imageFileName);
        //            // Convert integer oid to full oid
        //            rasterId = new ObjectId(oidInteger);
        //            // Get the new image object from the rasterId
        //            RasterImage rasterImage = trans.GetObject(rasterId, OpenMode.ForRead) as RasterImage;
        //            //RasterImage rasterImage = trans.GetObject(rasterId, OpenMode.ForWrite) as RasterImage;
        //            // Set layer and color
        //            rasterImage.UpgradeOpen();
        //            rasterImage.Layer = layerName;
        //            rasterImage.ColorIndex = colorIndex;
        //            trans.Commit();
        //        }
        //    }
        //    catch (System.Exception ex)
        //    {
        //        PGA.MessengerManager.MessengerManager.AddLog("Error in InsertRasterImageUsingTfw", ex);
        //        throw;
        //    }
        //    PGA.MessengerManager.MessengerManager.AddLog("End InsertRasterImageUsingTfw");
        //    return rasterId;
        //}

        /// <summary>
        ///     Sets the raster image clip frame.
        /// </summary>
        /// <param name="db">The db.</param>
        /// <param name="rasterImageId">The raster image id.</param>
        /// <param name="clipPoints">The clip points.</param>
        /// <returns></returns>
        /// <summary>
        ///     Gets all raster image objects.
        /// </summary>
        /// <param name="trans">The trans.</param>
        /// <returns></returns>
        /// <summary>
        ///     Deletes all raster image objects.
        /// </summary>
        /// <param name="db">The db.</param>
        /// <param name="trans">The trans.</param>
        /// <returns></returns>
        /// <summary>
        ///     Deletes the unreferenced raster image definitions.
        /// </summary>
        /// <param name="db">The db.</param>
        /// <param name="trans">The trans.</param>
        /// <returns></returns>
        public static bool DeleteUnreferencedRasterImageDefinitions(Database db, Transaction trans)
        {
            PGA.MessengerManager.MessengerManager.AddLog("Start DeleteUnreferencedRasterImageDefinitions");
            // Get the Image Dictionary
            var imageDictionaryId = RasterImageDef.GetImageDictionary(db);

            if (imageDictionaryId == ObjectId.Null)
            {
                // No images defined?
                PGA.MessengerManager.MessengerManager.AddLog("End DeleteUnreferencedRasterImageDefinitions");
                return(true);
            }

            var imageDictionary = (DBDictionary)trans.GetObject(imageDictionaryId, OpenMode.ForRead);

            if (imageDictionary.Count.Equals(0))
            {
                // No images defined?
                PGA.MessengerManager.MessengerManager.AddLog("End DeleteUnreferencedRasterImageDefinitions");
                return(true);
            }

            foreach (DictionaryEntry imageDictionaryEntry in imageDictionary)
            {
                var  imageName        = imageDictionaryEntry.Key as string;
                var  rasterImageDefId = (ObjectId)imageDictionaryEntry.Value;
                var  rasterImageDef   = trans.GetObject(rasterImageDefId, OpenMode.ForRead) as RasterImageDef;
                bool LockedLayers;
                var  rasterImageRefCount = rasterImageDef.GetEntityCount(out LockedLayers);
                if (rasterImageRefCount.Equals(0))
                {
                    rasterImageDef.Erase();
                }
            }
            PGA.MessengerManager.MessengerManager.AddLog("End DeleteUnreferencedRasterImageDefinitions");
            return(true);
        }
 private static void DefineImage(string luchtFotoFile, string dictName, ref RasterImageDef imageDef,
                                 ref ObjectId imageDefId, Database db, Transaction trans)
 {
     try
     {
         var imageDictionary = RasterImageDef.GetImageDictionary(db);
         // ISSUE: explicit reference operation
         var imageDict = trans.GetObject(imageDictionary, 0) as DBDictionary;
         if (imageDict != null && imageDict.Contains(dictName))
         {
             imageDefId = imageDict.GetAt(dictName);
             imageDef   = trans.GetObject(imageDefId, (OpenMode)1) as RasterImageDef;
         }
         else
         {
             CreateTheRasterFile(luchtFotoFile, dictName, ref imageDef, ref imageDefId, trans, imageDict);
         }
         imageDefId = CreateImage(imageDef, imageDefId, db, trans);
     }
     catch (Exception ex)
     {
         Utilities.HandleError(ex);
     }
 }
Example #10
0
        public void InputMap()
        {
            string WolrdMapName = "大世界";
            string layer        = "Ground";

            CurrentWorldMap = WolrdMapName;
            CurrentLayer    = layer;
            //line1 = new Line();
            //Point3d point1 = new Point3d(0, 0, 0);
            //Point3d point2 = new Point3d(100, 0, 0);
            //line1.StartPoint = point1;
            //line1.EndPoint = point2;

            //using (Transaction trans = db.TransactionManager.StartTransaction())
            //{

            //    btr.AppendEntity(line1);
            //    trans.AddNewlyCreatedDBObject(line1,true);
            //    trans.Commit();
            //}

            // Get the current database and start a transaction
            Database acCurDb;

            acCurDb = Application.DocumentManager.MdiActiveDocument.Database;

            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // Define the name and image to use


                RasterImageDef acRasterDef;
                bool           bRasterDefCreated = false;
                ObjectId       acImgDefId;

                // Get the image dictionary
                ObjectId acImgDctID = RasterImageDef.GetImageDictionary(acCurDb);

                // Check to see if the dictionary does not exist, it not then create it
                if (acImgDctID.IsNull)
                {
                    acImgDctID = RasterImageDef.CreateImageDictionary(acCurDb);
                }

                // Open the image dictionary
                DBDictionary acImgDict = acTrans.GetObject(acImgDctID, OpenMode.ForRead) as DBDictionary;


                ReadMapData();

                //创建世界地图的边缘矩形
                Document         doc = Application.DocumentManager.MdiActiveDocument;
                Database         db  = doc.Database;
                BlockTable       bt  = acTrans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = acTrans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                double worldWidth  = AllMap[CurrentWorldMap].width;
                double worldHeight = AllMap[CurrentWorldMap].height;

                Point2d p1 = new Point2d(0, 0);
                Point2d p2 = new Point2d(worldWidth, 0);
                Point2d p3 = new Point2d(worldWidth, worldHeight);
                Point2d p4 = new Point2d(0, worldHeight);
                Autodesk.AutoCAD.DatabaseServices.Polyline RectPoly = new Autodesk.AutoCAD.DatabaseServices.Polyline();
                RectPoly.AddVertexAt(0, p1, 0, 0, 0);
                RectPoly.AddVertexAt(1, p2, 0, 0, 0);
                RectPoly.AddVertexAt(2, p3, 0, 0, 0);
                RectPoly.AddVertexAt(3, p4, 0, 0, 0);

                RectPoly.Closed = true;
                WorldEdgeRect   = btr.AppendEntity(RectPoly);
                acTrans.AddNewlyCreatedDBObject(RectPoly, true);
                //Line line1 = new Line() { StartPoint = new Point3d(0, 0, 0), EndPoint = new Point3d(worldWidth, 0, 0) };
                //Line line2 = new Line() { StartPoint = new Point3d(0, worldWidth, 0), EndPoint = new Point3d(worldWidth, worldHeight, 0) };
                //Line line3 = new Line() { StartPoint = new Point3d(worldWidth, worldHeight, 0), EndPoint = new Point3d(0, worldHeight, 0) };
                //Line line4 = new Line() { StartPoint = new Point3d(0, worldHeight, 0), EndPoint = new Point3d(0, 0, 0) };
                //btr.AppendEntity(line1);
                //btr.AppendEntity(line2);
                //btr.AppendEntity(line3);
                //btr.AppendEntity(line4);
                //acTrans.AddNewlyCreatedDBObject(line1, true);
                //acTrans.AddNewlyCreatedDBObject(line2, true);
                //acTrans.AddNewlyCreatedDBObject(line3, true);
                //acTrans.AddNewlyCreatedDBObject(line4, true);
                //Entity ent1 = (Entity)line1;
                //Entity ent2 = (Entity)line2;
                //Entity ent3 = (Entity)line3;
                //Entity ent4 = (Entity)line4;
                //Group group = new Group();
                //group.Append(ent1.ObjectId);
                //group.Append(ent2.ObjectId);
                //group.Append(ent3.ObjectId);
                //group.Append(ent4.ObjectId);
                //DBDictionary groupdic = acTrans.GetObject(db.GroupDictionaryId, OpenMode.ForWrite) as DBDictionary;
                //group.Selectable = true;
                //group.Name = "mapEdge";
                //groupdic.SetAt(group.Name, group);
                //acTrans.AddNewlyCreatedDBObject(group, true);
                //~创建世界地图的边缘矩形
                foreach (var iter in AllMap[WolrdMapName].maps[layer])
                {
                    string strImgName  = iter.MapName;
                    string strFileName = mapDir + "\\" + iter.MapName + "\\" + layer + ".png";
                    if (acImgDict.Contains(strImgName))
                    {
                        acImgDefId = acImgDict.GetAt(strImgName);

                        acRasterDef = acTrans.GetObject(acImgDefId, OpenMode.ForWrite) as RasterImageDef;
                    }
                    else
                    {
                        // Create a raster image definition
                        RasterImageDef acRasterDefNew = new RasterImageDef();

                        // Set the source for the image file
                        acRasterDefNew.SourceFileName = strFileName;

                        // Load the image into memory
                        acRasterDefNew.Load();

                        // Add the image definition to the dictionary
                        acImgDict.UpgradeOpen();
                        acImgDefId = acImgDict.SetAt(strImgName, acRasterDefNew);

                        acTrans.AddNewlyCreatedDBObject(acRasterDefNew, true);

                        acRasterDef = acRasterDefNew;

                        bRasterDefCreated = true;
                    }

                    // Open the Block table for read
                    BlockTable acBlkTbl;
                    acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable;

                    // Open the Block table record Model space for write
                    BlockTableRecord acBlkTblRec;
                    acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
                                                    OpenMode.ForWrite) as BlockTableRecord;

                    // Create the new image and assign it the image definition
                    using (RasterImage acRaster = new RasterImage())
                    {
                        acRaster.ImageDefId = acImgDefId;
                        //image = acRaster;
                        // Use ImageWidth and ImageHeight to get the size of the image in pixels (1024 x 768).
                        // Use ResolutionMMPerPixel to determine the number of millimeters in a pixel so you
                        // can convert the size of the drawing into other units or millimeters based on the
                        // drawing units used in the current drawing.

                        // Define the width and height of the image
                        Vector3d width;
                        Vector3d height;

                        // Check to see if the measurement is set to English (Imperial) or Metric units
                        //if (acCurDb.Measurement == MeasurementValue.English)
                        //{
                        //width = new Vector3d((acRasterDef.ResolutionMMPerPixel.X * acRaster.ImageWidth) / 25.4, 0, 0);
                        //height = new Vector3d(0, (acRasterDef.ResolutionMMPerPixel.Y * acRaster.ImageHeight) / 25.4, 0);
                        //}
                        //else
                        //{

                        if (iter.width < 0)
                        {
                            iter.width = acRaster.ImageWidth;
                        }
                        if (iter.height < 0)
                        {
                            iter.height = acRaster.ImageHeight;
                        }
                        if (iter.x < 0)
                        {
                            iter.x = 0;
                        }
                        if (iter.y < 0)
                        {
                            iter.y = 0;
                        }
                        width  = new Vector3d(iter.width, 0, 0);
                        height = new Vector3d(0, iter.height, 0);
                        //}

                        // Define the position for the image
                        Point3d insPt = new Point3d(iter.x, iter.y, 0.0);

                        // Define and assign a coordinate system for the image's orientation
                        CoordinateSystem3d coordinateSystem = new CoordinateSystem3d(insPt, width, height);
                        acRaster.Orientation = coordinateSystem;

                        // Set the rotation angle for the image
                        acRaster.Rotation = 0;

                        // Add the new object to the block table record and the transaction
                        iter.ID = acBlkTblRec.AppendEntity(acRaster);
                        acTrans.AddNewlyCreatedDBObject(acRaster, true);

                        // Connect the raster definition and image together so the definition
                        // does not appear as "unreferenced" in the External References palette.
                        RasterImage.EnableReactors(true);
                        acRaster.AssociateRasterDef(acRasterDef);

                        if (bRasterDefCreated)
                        {
                            acRasterDef.Dispose();
                        }
                    }
                }
                // Save the new object to the database
                acTrans.Commit();

                // Dispose of the transaction
            }
        }
Example #11
0
        public ObjectId addImage(Document doc, double resulotion, int start_row, int end_row, int start_col, int end_col)
        {
            lockLayerOrNot(_layer_name, false);
            Database database = doc.Database;
            Editor   editor   = doc.Editor;
            ObjectId result;
            //try
            //{
            //    System.Drawing.Image.FromStream(new WebClient().OpenRead(url));
            //}
            //catch
            //{
            //    result = ObjectId.Null;
            //    editor.WriteMessage("Url is invalid!");
            //    return result;
            //}

            ObjectId objectId = ObjectId.Null;

            try
            {
                using (doc.LockDocument(DocumentLockMode.ProtectedAutoWrite, null, null, false))
                {
                    Autodesk.AutoCAD.ApplicationServices.TransactionManager transactionManager = doc.TransactionManager;
                    doc.TransactionManager.EnableGraphicsFlush(true);
                    using (Transaction transaction = transactionManager.StartTransaction())
                    {
                        ObjectId objectId2 = RasterImageDef.GetImageDictionary(database);
                        if (objectId2.IsNull)
                        {
                            objectId2 = RasterImageDef.CreateImageDictionary(database);
                        }
                        //rasterImageDef.ResolutionMMPerPixel = new Vector2d(78217.51696, 78217.51696);
                        DBDictionary dBDictionary = (DBDictionary)transaction.GetObject(objectId2, OpenMode.ForWrite);
                        dBDictionary.Erase();
                        for (int i = start_row; i <= end_row; ++i)
                        {
                            for (int j = start_col; j <= end_col; ++j)
                            {
                                Point2d        left_up        = MapTiles.webMercatorTilesLeftUpLocation(j, i, _level);
                                string         url            = string.Format("http://t3.tianditu.cn/img_c/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=c&TileMatrix={0}&TileRow={1}&TileCol={2}&style=default&format=tiles", _level, i, j);
                                RasterImageDef rasterImageDef = new RasterImageDef();
                                rasterImageDef.SourceFileName = (url);
                                rasterImageDef.Load();
                                bool arg_A4_0 = rasterImageDef.IsLoaded;

                                string text = RasterImageDef.SuggestName(dBDictionary, url);
                                if (dBDictionary.Contains(text))
                                {
                                    result = ObjectId.Null;
                                    return(result);
                                }
                                dBDictionary.SetAt(text, rasterImageDef);
                                transaction.AddNewlyCreatedDBObject(rasterImageDef, true);
                                string   layer_name = _layer_name;
                                ObjectId layer      = GetLayer(database, transaction, ref layer_name);

                                RasterImage rasterImage = new RasterImage();
                                rasterImage.ImageDefId = (rasterImageDef.ObjectId);
                                rasterImage.SetLayerId(layer, false);
                                //byte b = Convert.ToByte(Math.Floor((100.0 - (double)transparency) / 100.0 * 254.0));
                                Transparency transparency2 = new Autodesk.AutoCAD.Colors.Transparency(100);
                                rasterImage.Transparency = transparency2;
                                rasterImage.Orientation  = new CoordinateSystem3d(new Point3d(left_up.X, left_up.Y, 0), new Vector3d(resulotion * 256, 0, 0), new Vector3d(0, resulotion * 256, 0));
                                BlockTable       blockTable       = (BlockTable)transactionManager.GetObject(database.BlockTableId, 0, false);
                                BlockTableRecord blockTableRecord = (BlockTableRecord)transactionManager.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);

                                rasterImage.ColorIndex = (256);
                                objectId = blockTableRecord.AppendEntity(rasterImage);
                                transactionManager.AddNewlyCreatedDBObject(rasterImage, true);
                                rasterImage.AssociateRasterDef(rasterImageDef);
                                RasterImage.EnableReactors(true);
                                rasterImageDef.UpdateEntities();
                                try
                                {
                                    rasterImageDef.UpdateEntities();
                                }
                                catch (System.Exception ex)
                                {
                                }
                            }
                        }

                        //DrawOrderTable drawOrderTable = (DrawOrderTable)transaction.GetObject(blockTableRecord.DrawOrderTableId, OpenMode.ForWrite);
                        //ObjectIdCollection objectIdCollection = new ObjectIdCollection();
                        //objectIdCollection.Add(objectId);
                        //drawOrderTable.MoveToBottom(objectIdCollection);

                        transaction.Commit();
                    }
                }
                result = objectId;
            }
            catch (System.Exception ex)
            {
                string   message   = ex.Message;
                ObjectId arg_2FE_0 = ObjectId.Null;
                result = ObjectId.Null;
            }
            catch
            {
                //rrorReport.ShowErrorMessage(AfaStrings.UnexpectedErrorInAddingRasterImage);
                result = ObjectId.Null;
            }
            lockLayerOrNot(_layer_name, true);
            return(result);
        }
Example #12
0
        public ObjectId DefineRasterImage(Document doc, string url, Point3d basePoint, Vector3d v1, Vector3d v2, string suggestedName, byte transparency)
        {
            ObjectId result;

            try
            {
                System.Drawing.Image.FromStream(new WebClient().OpenRead(url));
            }
            catch
            {
                result = ObjectId.Null;
                return(result);
            }
            Database database = doc.Database;
            Editor   editor   = doc.Editor;
            ObjectId objectId = ObjectId.Null;
            ObjectId arg_39_0 = ObjectId.Null;

            try
            {
                using (doc.LockDocument(DocumentLockMode.ProtectedAutoWrite, null, null, false))
                {
                    Autodesk.AutoCAD.ApplicationServices.TransactionManager transactionManager = doc.TransactionManager;
                    doc.TransactionManager.EnableGraphicsFlush(true);
                    using (Transaction transaction = transactionManager.StartTransaction())
                    {
                        string.IsNullOrEmpty(suggestedName);
                        ObjectId objectId2 = RasterImageDef.GetImageDictionary(database);
                        if (objectId2.IsNull)
                        {
                            objectId2 = RasterImageDef.CreateImageDictionary(database);
                        }
                        RasterImageDef rasterImageDef = new RasterImageDef();
                        rasterImageDef.SourceFileName = (url);
                        rasterImageDef.Load();
                        bool         arg_A4_0     = rasterImageDef.IsLoaded;
                        DBDictionary dBDictionary = (DBDictionary)transaction.GetObject(objectId2, OpenMode.ForWrite);
                        string       text         = RasterImageDef.SuggestName(dBDictionary, url);
                        if (!string.IsNullOrEmpty(suggestedName))
                        {
                            text = suggestedName;
                            int num = 0;
                            while (dBDictionary.Contains(text))
                            {
                                num++;
                                text = suggestedName + num;
                            }
                        }
                        ObjectId arg_F8_0 = ObjectId.Null;
                        if (dBDictionary.Contains(text))
                        {
                            //editor.WriteMessage(AfaStrings.ImageAlreadyExits);
                            result = ObjectId.Null;
                            return(result);
                        }
                        dBDictionary.SetAt(text, rasterImageDef);
                        transaction.AddNewlyCreatedDBObject(rasterImageDef, true);
                        dBDictionary.Contains(text);
                        ObjectId    layer       = GetLayer(database, transaction, ref text);
                        RasterImage rasterImage = new RasterImage();
                        rasterImage.ImageDefId = (rasterImageDef.ObjectId);
                        rasterImage.SetLayerId(layer, false);
                        byte         b             = Convert.ToByte(Math.Floor((100.0 - (double)transparency) / 100.0 * 254.0));
                        Transparency transparency2 = new Transparency(b);
                        rasterImage.Transparency = transparency2;
                        ;                       rasterImage.Orientation = new CoordinateSystem3d(basePoint, v1, v2);
                        BlockTable       blockTable       = (BlockTable)transactionManager.GetObject(database.BlockTableId, 0, false);
                        BlockTableRecord blockTableRecord = (BlockTableRecord)transactionManager.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
                        int num2 = 0;
                        try
                        {
                            num2 = blockTableRecord.Cast <object>().Count <object>();
                        }
                        catch
                        {
                        }
                        rasterImage.ColorIndex = (256);
                        objectId = blockTableRecord.AppendEntity(rasterImage);
                        transactionManager.AddNewlyCreatedDBObject(rasterImage, true);
                        rasterImage.AssociateRasterDef(rasterImageDef);
                        RasterImage.EnableReactors(true);
                        rasterImageDef.UpdateEntities();
                        DrawOrderTable     drawOrderTable     = (DrawOrderTable)transaction.GetObject(blockTableRecord.DrawOrderTableId, OpenMode.ForWrite);
                        ObjectIdCollection objectIdCollection = new ObjectIdCollection();
                        objectIdCollection.Add(objectId);
                        drawOrderTable.MoveToBottom(objectIdCollection);
                        try
                        {
                            rasterImageDef.UpdateEntities();
                            if (num2 == 0)
                            {
                                ZoomExtents(rasterImage.GeometricExtents.MinPoint, rasterImage.GeometricExtents.MaxPoint);
                                editor.WriteMessage(rasterImage.Orientation.Origin.ToString());
                            }
                        }
                        catch
                        {
                        }
                        transaction.Commit();
                    }
                }
                result = objectId;
            }
            catch (System.Exception ex)
            {
                result = ObjectId.Null;
            }
            catch
            {
                //rrorReport.ShowErrorMessage(AfaStrings.UnexpectedErrorInAddingRasterImage);
                result = ObjectId.Null;
            }
            return(result);
        }
Example #13
0
        public void AttachRasterImage()

        {
            // Get the current database and start a transaction

            Database db = Application.DocumentManager.MdiActiveDocument.Database;

            using (Transaction tr = db.TransactionManager.StartTransaction())

            {
                // Define the name and image to use

                string strImgName = "Organica_Logo";

                string strFileName = @"E:\Munka\OrganiCad\DrawingTemplates\Images\Organica_Logo.png";

                RasterImageDef acRasterDef;

                bool bRasterDefCreated = false;

                ObjectId acImgDefId;

                // Get the image dictionary

                ObjectId acImgDctID = RasterImageDef.GetImageDictionary(db);

                // Check to see if the dictionary does not exist, it not then create it

                if (acImgDctID.IsNull)

                {
                    acImgDctID = RasterImageDef.CreateImageDictionary(db);
                }

                // Open the image dictionary

                DBDictionary acImgDict = tr.GetObject(acImgDctID, OpenMode.ForRead) as DBDictionary;

                // Check to see if the image definition already exists

                if (acImgDict.Contains(strImgName))

                {
                    acImgDefId = acImgDict.GetAt(strImgName);

                    acRasterDef = tr.GetObject(acImgDefId,

                                               OpenMode.ForWrite) as RasterImageDef;
                }

                else

                {
                    // Create a raster image definition

                    RasterImageDef acRasterDefNew = new RasterImageDef();

                    // Set the source for the image file

                    acRasterDefNew.SourceFileName = strFileName;

                    // Load the image into memory

                    acRasterDefNew.Load();

                    // Add the image definition to the dictionary

                    acImgDict.UpgradeOpen();

                    acImgDefId = acImgDict.SetAt(strImgName, acRasterDefNew);

                    tr.AddNewlyCreatedDBObject(acRasterDefNew, true);

                    acRasterDef = acRasterDefNew;

                    bRasterDefCreated = true;
                }

                // Open the Block table for read

                BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                // Open the Block table record Model space for write

                BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.PaperSpace], OpenMode.ForWrite) as BlockTableRecord;

                // Create the new image and assign it the image definition

                using (RasterImage acRaster = new RasterImage())

                {
                    acRaster.ImageDefId = acImgDefId;

                    // Use ImageWidth and ImageHeight to get the size of the image in pixels (1024 x 768).

                    // Use ResolutionMMPerPixel to determine the number of millimeters in a pixel so you

                    // can convert the size of the drawing into other units or millimeters based on the

                    // drawing units used in the current drawing.

                    // Define the width and height of the image

                    Vector3d width;

                    Vector3d height;

                    // Check to see if the measurement is set to English (Imperial) or Metric units

                    if (db.Measurement == MeasurementValue.English)

                    {
                        width = new Vector3d((acRasterDef.ResolutionMMPerPixel.X * acRaster.ImageWidth) / 25.4, 0, 0);

                        height = new Vector3d(0, (acRasterDef.ResolutionMMPerPixel.Y * acRaster.ImageHeight) / 25.4, 0);
                    }

                    else

                    {
                        width = new Vector3d(acRasterDef.ResolutionMMPerPixel.X * acRaster.ImageWidth, 0, 0);

                        height = new Vector3d(0, acRasterDef.ResolutionMMPerPixel.Y * acRaster.ImageHeight, 0);
                    }

                    // Define the position for the image

                    Point3d insPt = new Point3d(12.0, 12.0, 0.0);

                    // Define and assign a coordinate system for the image's orientation

                    CoordinateSystem3d coordinateSystem = new CoordinateSystem3d(insPt, width * 2, height * 2);

                    acRaster.Orientation = coordinateSystem;

                    // Set the rotation angle for the image

                    acRaster.Rotation = 0;

                    // Add the new object to the block table record and the transaction

                    btr.AppendEntity(acRaster);

                    tr.AddNewlyCreatedDBObject(acRaster, true);

                    // Connect the raster definition and image together so the definition

                    // does not appear as "unreferenced" in the External References palette.

                    RasterImage.EnableReactors(true);

                    acRaster.AssociateRasterDef(acRasterDef);

                    if (bRasterDefCreated)
                    {
                        acRasterDef.Dispose();
                    }
                }

                // Save the new object to the database

                tr.Commit();

                // Dispose of the transaction
            }
        }
Example #14
0
        private static RasterImage CreateRasterImage(string uri, double sz)
        {
            Document doc =
                Application.DocumentManager.MdiActiveDocument;
            Editor   ed = doc.Editor;
            Database db = doc.Database;

            Transaction tr = db.TransactionManager.StartTransaction();

            using (tr)
            {
                // Get the image dictionary's ID, if it already exists

                ObjectId dictId = RasterImageDef.GetImageDictionary(db);

                if (dictId.IsNull) // If it doesn't, create a new one
                {
                    dictId = RasterImageDef.CreateImageDictionary(db);
                }

                // Open the image dictionary

                DBDictionary dict =
                    (DBDictionary)tr.GetObject(dictId, OpenMode.ForRead);

                // Get a unique record name for our raster image definition

                int    i       = 0;
                string defName =
                    APPLICATION_PREFIX + i.ToString();

                while (dict.Contains(defName))
                {
                    i++;
                    defName = APPLICATION_PREFIX + i.ToString();
                }
                RasterImageDef rid = new RasterImageDef();
                try
                {
                    // Set its source image and load it
                    rid.SourceFileName = uri;
                    rid.Load();
                }
                catch
                {
                    ed.WriteMessage(
                        "\nUnable to create image object. " +
                        "Here is the URL to the image: {0}",
                        uri
                        );
                    System.Diagnostics.Process.Start(uri);
                    return(null);
                }

                // Put the definition in the dictionary

                dict.UpgradeOpen();
                ObjectId defId = dict.SetAt(defName, rid);

                // Let the transaction know about it

                tr.AddNewlyCreatedDBObject(rid, true);

                RasterImage ri = new RasterImage();
                ri.ImageDefId = defId;

                // Resize

                ri.TransformBy(Matrix3d.Scaling(sz / 500.0, Point3d.Origin));

                AppendEntityToCurrentSpace(ri);

                // Create a reactor between the RasterImage and the
                // RasterImageDef to avoid the "unreferenced"
                // warning in the XRef palette

                RasterImage.EnableReactors(true);
                ri.AssociateRasterDef(rid);

                tr.Commit();

                return(ri);
            }
        }
Example #15
0
        public static void EditQR()
        {
            Document doc =
                Application.DocumentManager.MdiActiveDocument;
            Editor   ed = doc.Editor;
            Database db = doc.Database;

            // Ask user to select an QR code, hatch or raster image

            PromptEntityOptions peo =
                new PromptEntityOptions("Select a QR code: ");

            peo.SetRejectMessage(
                "\nMust be a hatch or a raster image"
                );
            peo.AddAllowedClass(typeof(Hatch), true);

            // AutoCAD crash if we try AddAllowedClass for RasterImage
            // when no raster image is defined or just hatch QRs were
            // defined, probably because in C++ we need to call
            // acedArxLoad("acismui.arx"), which is not exposed in .NET,
            // so let's check before if the drawing contains any
            // RasterImages, if not we don't need this filter.

            if (!RasterImageDef.GetImageDictionary(db).IsNull)
            {
                peo.AddAllowedClass(typeof(RasterImage), true);
            }
            PromptEntityResult entityResult = ed.GetEntity(peo);

            if (entityResult.Status != PromptStatus.OK)
            {
                return;
            }

            Transaction tr = db.TransactionManager.StartTransaction();

            using (tr)
            {
                Entity ent =
                    tr.GetObject(entityResult.ObjectId, OpenMode.ForRead)
                    as Entity;
                ResultBuffer rb =
                    ent.GetXDataForApplication(APPLICATION_PREFIX);

                if (rb != null && rb.AsArray().Length == 0)
                {
                    ed.WriteMessage("\nThis is not a valid QR code");
                    tr.Commit(); //faster
                    return;
                }

                // Show the form with current information

                QRCodeForm form = new QRCodeForm();
                form.IsEditing = true;
                form.QREncodeDataAsResultBuffer = rb;
                rb.Dispose();
                System.Windows.Forms.DialogResult res =
                    Application.ShowModalDialog(form);
                if (res != System.Windows.Forms.DialogResult.OK)
                {
                    return;
                }

                //Get insert point and size

                double size =
                    ent.GeometricExtents.MaxPoint.X -
                    ent.GeometricExtents.MinPoint.X;
                Point3d inspt = ent.GeometricExtents.MinPoint;


                if (ent is RasterImage)
                {
                    // Just update the raster image definition

                    RasterImage    image    = ent as RasterImage;
                    RasterImageDef imageDef =
                        tr.GetObject(image.ImageDefId, OpenMode.ForWrite)
                        as RasterImageDef;
                    imageDef.SourceFileName =
                        FormatDataHelper.EncodeQrCodeUrl(form.QREncodeData);
                    imageDef.Load();
                }
                else
                {
                    // Erase current entity

                    ent.UpgradeOpen();
                    ent.Erase();

                    // Create a new one

                    Entity newEnt =
                        GenerateQRHatch(
                            form.QREncodeData, form.QREncode,
                            form.QRVersion, form.QRErrorCorrect, (int)size
                            );
                    if (newEnt == null)
                    {
                        return;
                    }
                    ResultBuffer newRb = form.QREncodeDataAsResultBuffer;
                    newEnt.XData = newRb;
                    newRb.Dispose();
                    newEnt.TransformBy(
                        Matrix3d.Displacement(inspt.GetAsVector())
                        );
                    AppendEntityToCurrentSpace(newEnt);
                }

                tr.Commit();
            }
        }
Example #16
0
        public void OutputMap()
        {
            //Point3d p = line1.StartPoint;

            Database acCurDb;

            acCurDb = Application.DocumentManager.MdiActiveDocument.Database;
            // Get the image dictionary
            ObjectId acImgDctID = RasterImageDef.GetImageDictionary(acCurDb);

            // Check to see if the dictionary does not exist, it not then create it
            if (acImgDctID.IsNull)
            {
                acImgDctID = RasterImageDef.CreateImageDictionary(acCurDb);
            }
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                Autodesk.AutoCAD.DatabaseServices.Polyline Rect = WorldEdgeRect.GetObject(OpenMode.ForRead) as Autodesk.AutoCAD.DatabaseServices.Polyline;
                Point2d pmax = Rect.GetPoint2dAt(2);
                AllMap[CurrentWorldMap].width  = pmax.X;
                AllMap[CurrentWorldMap].height = pmax.Y;
                foreach (var Map in AllMap[CurrentWorldMap].maps[CurrentLayer])
                {
                    if (!Map.ID.IsNull)
                    {
                        //acRasterDef = acTrans.GetObject(ID, OpenMode.ForWrite) as RasterImageDef;
                        //}
                        //RasterImage image = new RasterImage();
                        //image.ImageDefId = ID;
                        //Point3d p2 = image.Position;
                        RasterImage image = null;
                        image = Map.ID.GetObject(OpenMode.ForRead) as RasterImage;
                        if (image != null)
                        {
                            Point3d p = image.Orientation.Origin;
                            Map.x     = p.X;
                            Map.y     = p.Y;
                            Map.width = image.Width;
                            double width2 = image.ImageWidth;
                            Map.height = image.Height;
                            double height2 = image.ImageHeight;
                        }
                    }
                }
                WriteMapData();
                // Open the Block table for read
                BlockTable acBlkTbl;
                acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable;

                // Open the Block table record Model space for write
                BlockTableRecord acBlkTblRec;
                acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
                                                OpenMode.ForRead) as BlockTableRecord;
                System.Drawing.Image img = null;
                string name = acBlkTblRec.Name;
                if (!String.IsNullOrEmpty(name))
                {
                    img = GetBlockImageFromDrawing(name);
                }
                string path = mapDir + "\\" + CurrentWorldMap + "_" + CurrentLayer + ".bmp";
                if (File.Exists(path))
                {
                    try
                    {
                        File.Delete(path);
                    }
                    catch (System.Exception ex)
                    {
                        ed.WriteMessage(path + "  被占用,请重试");
                    }
                }
                try
                {
                    if (img != null)
                    {
                        img.Save(path);
                    }
                }
                catch (System.Exception ex)
                {
                    ed.WriteMessage(path + "  被占用,请重试");
                }
            }
        }
Example #17
0
        public bool newImg()
        {
            DocumentLock doclock = null;

            try
            {
                Document doc = Application.DocumentManager.MdiActiveDocument;
                doclock = doc.LockDocument();

                Database db = HostApplicationServices.WorkingDatabase;

                ObjectId bjdtId = ElectronTransferDal.Cad.DCadApi.addLayer("背景地图");
                if (bjdtId != ObjectId.Null)
                {
                    db.Clayer = bjdtId;

                    Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;

                    using (Transaction t = tm.StartTransaction())
                    {
                        try
                        {
                            var          imgDictID = RasterImageDef.GetImageDictionary(db);
                            DBDictionary imgDict;
                            if (imgDictID.OldId == 0)
                            {
                                imgDictID = RasterImageDef.CreateImageDictionary(db);
                            }

                            // create the raster image definition
                            RasterImageDef rasterDef = new RasterImageDef();

                            rasterDef.SourceFileName = ImgFullName;
                            rasterDef.Load();

                            // test the image dictionary and the raster before going further
                            bool bTestLoad = rasterDef.IsLoaded;

                            imgDict = (DBDictionary)t.GetObject(imgDictID, OpenMode.ForWrite);

                            // add the raster definition to the dictionary iff it doesn't already exist
                            ObjectId rasterDefID;
                            if (!imgDict.Contains(ImgName))
                            {
                                rasterDefID = imgDict.SetAt(ImgName, rasterDef);
                            }

                            t.AddNewlyCreatedDBObject(rasterDef, true);

                            // now add the REAL raster image reference
                            RasterImage rasterRef = new RasterImage();
                            rasterRef.ImageDefId = rasterDef.ObjectId;
                            ObjectId testRefID = rasterRef.ObjectId;

                            BlockTable       bt  = (BlockTable)tm.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                            BlockTableRecord btr = (BlockTableRecord)tm.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
                            btr.AppendEntity(rasterRef);

                            tm.AddNewlyCreatedDBObject(rasterRef, true);

                            rasterRef.AssociateRasterDef(rasterDef);

                            parEntityId = rasterRef.ObjectId;
                        }
                        catch (Autodesk.AutoCAD.Runtime.Exception eex)
                        { }
                        catch (System.Exception ex) { }

                        t.Commit();
                    }
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception eex)
            {
                return(false);
            }
            catch (System.Exception ex) { return(false); }
            finally
            {
                doclock.Dispose();
            }

            return(true);
        }
Example #18
0
        public bool DeleteService()
        {
            try
            {
                base.StopReactors();
                base.StopReactors();
            }
            catch
            {
            }
            Database database       = base.ParentDataset.ParentDocument.Database;
            Document parentDocument = base.ParentDataset.ParentDocument;
            Editor   editor         = base.ParentDataset.ParentDocument.Editor;
            bool     result;

            try
            {
                using (base.ParentDataset.ParentDocument.LockDocument((DocumentLockMode)20, null, null, false))
                {
                    using (Transaction transaction = parentDocument.TransactionManager.StartTransaction())
                    {
                        RasterImage rasterImage = (RasterImage)transaction.GetObject(base.RasterObjectId, (OpenMode)1);
                        rasterImage.DisableUndoRecording(true);
                        ObjectId       imageDefId     = rasterImage.ImageDefId;
                        RasterImageDef rasterImageDef = (RasterImageDef)transaction.GetObject(imageDefId, (OpenMode)1);
                        rasterImageDef.DisableUndoRecording(true);
                        if (rasterImageDef.IsLoaded)
                        {
                            rasterImageDef.Unload(true);
                        }
                        try
                        {
                            File.Delete(rasterImageDef.SourceFileName);
                            if (App.TempFiles.Contains(rasterImageDef.SourceFileName))
                            {
                                App.TempFiles.Remove(rasterImageDef.SourceFileName);
                            }
                        }
                        catch
                        {
                        }
                        if (!rasterImageDef.IsErased)
                        {
                            rasterImageDef.Erase();
                        }
                        ObjectId     imageDictionary = RasterImageDef.GetImageDictionary(database);
                        DBDictionary dBDictionary    = (DBDictionary)transaction.GetObject(imageDictionary, (OpenMode)1);
                        dBDictionary.Remove(imageDefId);
                        dBDictionary.Contains(imageDefId);
                        if (!rasterImage.IsErased)
                        {
                            rasterImage.Erase(false);
                        }
                        this.RemoveDictionary(database, transaction);
                        parentDocument.TransactionManager.QueueForGraphicsFlush();
                        parentDocument.TransactionManager.FlushGraphics();
                        parentDocument.Editor.UpdateScreen();
                        transaction.Commit();
                        base.ParentDataset.ImageServices.Remove(base.Name);
                        editor.Regen();
                        MSCDataset.SetDefaultActiveRasterServices();
                        result = true;
                    }
                }
            }
            catch
            {
                MessageBox.Show("DEBUG:  Catch in MSCMapService.DeleteService");
                result = false;
            }
            return(result);
        }
Example #19
0
        private void InsertDownloadedImageToDocument(MapSource mapSource, AerialImageData imageData)
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

            ed.WriteMessage("Image downloaded to: " + imageData.FileName + '\n');

            Transaction tx = ed.Document.Database.TransactionManager.StartTransaction();

            try
            {
                // Lock the document
                Application.DocumentManager.MdiActiveDocument.LockDocument();

                // Get the document database
                Database dwg = Application.DocumentManager.MdiActiveDocument.Database;

                // Get the raster image dictionary id.
                // Create it if it's null.
                ObjectId imageDictId = RasterImageDef.GetImageDictionary(dwg);

                if (imageDictId.IsNull)
                {
                    imageDictId = RasterImageDef.CreateImageDictionary(dwg);
                }

                // Open the image dictionary
                DBDictionary imageDict = tx.GetObject(imageDictId, OpenMode.ForWrite) as DBDictionary;

                // Get the image's name, i.e. Aerial for C:\Aerial.jpg
                string imageName = Path.GetFileName(imageData.FileName).Split('.')[0];

                // Add the image to the dictionary, if it's not already present.
                RasterImageDef rasterImageDef;
                ObjectId       imageDefId;
                bool           rasterDefCreated = false;
                if (imageDict.Contains(imageName))
                {
                    // Get the image reference from the image dictionary.
                    imageDefId     = imageDict.GetAt(imageName);
                    rasterImageDef = tx.GetObject(imageDefId, OpenMode.ForWrite) as RasterImageDef;
                }
                else
                {
                    // Create the raster image definition
                    RasterImageDef newImageDef = new RasterImageDef
                    {
                        SourceFileName = imageData.FileName
                    };

                    // Load the image into the definition
                    newImageDef.Load();

                    // Write the image to the image dictionary
                    imageDict.UpgradeOpen();
                    imageDefId = imageDict.SetAt(imageName, newImageDef);

                    // Notify the transaction of the change.
                    tx.AddNewlyCreatedDBObject(newImageDef, true);

                    rasterImageDef   = newImageDef;
                    rasterDefCreated = true;
                }

                // Open the block table to get the model space ID
                BlockTable bt = tx.GetObject(dwg.BlockTableId, OpenMode.ForRead) as BlockTable;

                // Open the block table record for the model space.
                BlockTableRecord btr = tx.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                // Create the new image and assign it the image definition
                using (RasterImage image = new RasterImage())
                {
                    image.ImageDefId = imageDefId;

                    // Get the scale for the image
                    double width  = DegreesToFeet(Math.Abs(imageData.SWCorner.lng - imageData.NECorner.lng));
                    double height = rasterImageDef.Size.Y * (width / rasterImageDef.Size.X);

                    ed.WriteMessage($"Using {width} for width, and {height} for height.\n");

                    PromptKeywordOptions promptInsPtOpt    = new PromptKeywordOptions("Select insert type [Origin/Real/Choose] <O> : ", "Origin Real Choose");
                    PromptResult         promptInsPtOptRes = ed.GetKeywords(promptInsPtOpt);

                    // Insert the image at the reference point
                    Point3d?insertPt = null;

                    if (promptInsPtOptRes.Status == PromptStatus.OK)
                    {
                        switch (promptInsPtOptRes.StringResult)
                        {
                        case "Real":
                            insertPt = new Point3d(DegreesToFeet(imageData.SWCorner.lat),
                                                   DegreesToFeet(imageData.SWCorner.lng), 0);
                            break;

                        case "Choose":
                            PromptPointOptions insertPtOptions = new PromptPointOptions("Select insert point : ");
                            PromptPointResult  insertPtRes     = ed.GetPoint(insertPtOptions);

                            if (insertPtRes.Status == PromptStatus.OK)
                            {
                                insertPt = insertPtRes.Value;
                            }
                            break;
                        }
                    }

                    if (insertPt == null)
                    {
                        insertPt = new Point3d(0, 0, 0);
                    }

                    // Create the coordinate system to define the width and height.
                    // Otherwise, they will default to the image size in pixels.
                    image.Orientation = new CoordinateSystem3d(insertPt.Value,
                                                               new Vector3d(width, 0, 0), new Vector3d(0, height, 0));

                    // Set the rotation angle for the image.
                    image.Rotation = 0;

                    // Add the new object to the block table (must come before adding extension dict!)
                    btr.AppendEntity(image);

                    // Add the extension dictionary with associated image data.
                    if (image.ExtensionDictionary.IsNull)
                    {
                        image.CreateExtensionDictionary();
                    }

                    DBDictionary extDict = tx.GetObject(image.ExtensionDictionary, OpenMode.ForWrite) as DBDictionary;

                    // Create the Xrecord and result buffer with TypedValue array
                    Xrecord record = new Xrecord();
                    record.Data = new ResultBuffer(new TypedValue[]
                    {
                        new TypedValue((int)DxfCode.Real, imageData.Center.lat),
                        new TypedValue((int)DxfCode.Real, imageData.Center.lng),
                        new TypedValue((int)DxfCode.Real, imageData.NECorner.lat),
                        new TypedValue((int)DxfCode.Real, imageData.NECorner.lng),
                        new TypedValue((int)DxfCode.Real, imageData.SWCorner.lat),
                        new TypedValue((int)DxfCode.Real, imageData.SWCorner.lng),
                        new TypedValue((int)DxfCode.Int32, imageData.Zoom),
                        new TypedValue((int)DxfCode.Int32, (int)imageData.MapType),
                        new TypedValue((int)DxfCode.Int32, (int)mapSource),
                    });

                    extDict.SetAt("ImageData", record);

                    // Add the new objects to the transaction
                    tx.AddNewlyCreatedDBObject(image, true);
                    tx.AddNewlyCreatedDBObject(record, true);

                    // Connect the raster definition and image together so the definition
                    // does not appear as "unreferenced" in the External References palette
                    RasterImage.EnableReactors(true);
                    image.AssociateRasterDef(rasterImageDef);

                    if (rasterDefCreated)
                    {
                        rasterImageDef.Dispose();
                    }
                }

                tx.Commit();

                // TODO: Zoom to aerial
            }
            catch (Exception ex)
            {
                ed.WriteMessage("An error occurred inserting the image: " + ex.Message + '\n');
                ed.WriteMessage("Please try again.\n");
            } finally
            {
                tx.Dispose();
            }
        }
Example #20
0
        public static ObjectId addStaticGoogleMap()
        {
            var dialog = new OpenFileDialog("选择文件存储位置", "燃气热源方案比选", "jpg;png;bmp;*", "SaveFile", OpenFileDialog.OpenFileDialogFlags.NoShellExtensions);

            //var dialog = new OpenFileDialog();

            System.Windows.Forms.DialogResult result = dialog.ShowDialog();
            if (result != System.Windows.Forms.DialogResult.OK)
            {
                return(ObjectId.Null);
            }
            ObjectId val       = ObjectId.Null;
            string   imagePath = dialog.Filename;
            string   szname    = "import";

            Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();
            Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            using (Database db = doc.Database)
            {
                using (Transaction tm = db.TransactionManager.StartTransaction())
                {
                    try
                    {
                        ObjectId imageDictID = RasterImageDef.GetImageDictionary(db);
                        if (imageDictID == ObjectId.Null)
                        {
                            imageDictID = RasterImageDef.CreateImageDictionary(db);
                        }
                        RasterImageDef rasterImageDef = new RasterImageDef();
                        DBDictionary   imageDict      = (DBDictionary)tm.GetObject(imageDictID, OpenMode.ForWrite);
                        ObjectId       rasterImageDefID;
                        if (imageDict.Contains(szname))
                        {
                            rasterImageDefID = imageDict.GetAt(szname);
                            rasterImageDef   = (RasterImageDef)tm.GetObject(rasterImageDefID, OpenMode.ForWrite);
                        }
                        else
                        {
                            rasterImageDefID = imageDict.SetAt(szname, rasterImageDef);
                            rasterImageDef.SourceFileName = imagePath;
                            rasterImageDef.Load();
                            rasterImageDef.ImageModified   = true;
                            rasterImageDef.ResolutionUnits = Unit.Millimeter;

                            tm.AddNewlyCreatedDBObject(rasterImageDef, true);
                        }
                        RasterImage rasterImage = new RasterImage();
                        RasterImage.EnableReactors(true);
                        rasterImage.ImageDefId = rasterImageDef.ObjectId;
                        LayerTable lt = (LayerTable)tm.GetObject(db.LayerTableId, OpenMode.ForRead);
                        foreach (ObjectId objId in lt)
                        {
                            LayerTableRecord layer = tm.GetObject(objId, OpenMode.ForWrite) as LayerTableRecord;

                            if (layer.Name != "our_outline_layer" && !layer.Name.StartsWith("方案") && layer.IsErased == false)
                            {
                                rasterImage.LayerId = objId;
                                break;
                            }
                        }
                        BlockTable       bt  = (BlockTable)tm.GetObject(doc.Database.BlockTableId, OpenMode.ForRead, false);
                        BlockTableRecord btr = (BlockTableRecord)tm.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
                        val = btr.AppendEntity(rasterImage);
                        tm.AddNewlyCreatedDBObject(rasterImage, true);
                        tm.Commit();
                        tm.Dispose();
                    }
                    catch (System.Exception e)
                    {
                        System.Windows.Forms.MessageBox.Show(e.ToString());
                    }
                }
            }
            return(val);
        }