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); }
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); }
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(); } }
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); }
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); }
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); } }
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 + " 被占用,请重试"); } } }
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 } }
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(); } }
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); }
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); }
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 } }