/// <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); } } } } } }
void tttttt(object oo) { try { RasterImageDef __rasterDef = (RasterImageDef)oo; __rasterDef.Load(); } catch (System.Exception ex) { } }
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(); } }
private static ObjectId CreateImage(Transaction transaction, FileInfo imageFileinfo, DBDictionary imageDictionaryForRead, string imageName) { var acRasterDefNew = new RasterImageDef { SourceFileName = imageFileinfo.FullName }; acRasterDefNew.Load(); imageDictionaryForRead.UpgradeOpen(); var imageId = imageDictionaryForRead.SetAt(imageName, acRasterDefNew); transaction.AddNewlyCreatedDBObject(acRasterDefNew, true); return(imageId); }
private static void CreateTheRasterFile(string luchtFotoFile, string dictName, ref RasterImageDef imageDef, ref ObjectId imageDefId, Transaction trans, DBDictionary imageDict) { var openFileDialog = new OpenFileDialog("Open an Image file", luchtFotoFile, "tif", "Image File", OpenFileDialog.OpenFileDialogFlags.NoUrls); if (openFileDialog.ShowDialog() != DialogResult.OK) { return; } imageDef = new RasterImageDef { SourceFileName = openFileDialog.Filename }; imageDef.Load(); imageDict.UpgradeOpen(); imageDefId = imageDict.SetAt(dictName, imageDef); trans.AddNewlyCreatedDBObject(imageDef, true); }
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 bool UpdateRasterImage(Document doc, ObjectId rasterId, string url, Point3d basePoint, Vector3d v1, Vector3d v2) { bool result; try { if (doc == null) { result = false; } else { if (doc.IsDisposed) { result = false; } else { if (rasterId.IsEffectivelyErased) { result = false; } else { if (rasterId == ObjectId.Null) { result = false; } else { Database arg_4D_0 = doc.Database; try { Editor arg_54_0 = doc.Editor; ; using (doc.LockDocument(DocumentLockMode.Write, null, null, false)) { doc.TransactionManager.EnableGraphicsFlush(true); Autodesk.AutoCAD.ApplicationServices.TransactionManager transactionManager = doc.TransactionManager; using (Transaction transaction = transactionManager.StartTransaction()) { RasterImage rasterImage = (RasterImage)transaction.GetObject(rasterId, OpenMode.ForWrite); rasterImage.DisableUndoRecording(true); ObjectId imageDefId = rasterImage.ImageDefId; RasterImageDef rasterImageDef = (RasterImageDef)transaction.GetObject(imageDefId, OpenMode.ForWrite); rasterImageDef.DisableUndoRecording(true); string sourceFileName = rasterImageDef.SourceFileName; try { rasterImageDef.Unload(true); rasterImageDef.SourceFileName = url; rasterImageDef.Load(); if (rasterImageDef.IsLoaded) { try { if (!string.IsNullOrEmpty(sourceFileName)) { System.IO.File.Delete(sourceFileName); } } catch { } } //rasterImage.Orientation = new CoordinateSystem3d(basePoint, v1, v2); rasterImage.Draw(); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString()); } try { rasterImageDef.UpdateEntities(); doc.TransactionManager.QueueForGraphicsFlush(); doc.TransactionManager.FlushGraphics(); doc.Editor.UpdateScreen(); } catch { } transaction.Commit(); } } result = true; } catch (System.Exception) { result = false; } } } } } } catch { result = false; } return(result); }
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); }
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); }
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 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(); } }
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 } }
public void UpdateAerial() { Document doc = Application.DocumentManager.MdiActiveDocument; if (doc == null) { return; } Editor ed = doc.Editor; // Select an aerial entity to update PromptEntityResult entityResult = ed.GetEntity("Pick an aerial to update : "); if (entityResult.Status == PromptStatus.OK) { // Create a new transaction to contain the update Transaction tx = doc.TransactionManager.StartTransaction(); try { // Get the aerial entity object and try to read its extension dictionary RasterImage aerialEnt = tx.GetObject(entityResult.ObjectId, OpenMode.ForRead) as RasterImage; if (aerialEnt.ExtensionDictionary.IsNull) { throw new Exception(ErrorStatus.InvalidInput, "Unrecognized aerial image."); } // Get the extension dictionary object DBDictionary extDict = tx.GetObject(aerialEnt.ExtensionDictionary, OpenMode.ForRead) as DBDictionary; if (!extDict.Contains("ImageData")) { throw new Exception(ErrorStatus.InvalidInput, "Unrecognized aerial image."); } // Get the associated image data ObjectId boundsEntryId = extDict.GetAt("ImageData"); Xrecord boundsRecord = tx.GetObject(boundsEntryId, OpenMode.ForRead) as Xrecord; TypedValue[] resBuff = boundsRecord.Data.AsArray(); GeoPoint center = new GeoPoint((resBuff[0].Value as double?).Value, (resBuff[1].Value as double?).Value); GeoPoint neCorner = new GeoPoint((resBuff[2].Value as double?).Value, (resBuff[3].Value as double?).Value); GeoPoint swCorner = new GeoPoint((resBuff[4].Value as double?).Value, (resBuff[5].Value as double?).Value); int zoom = (resBuff[6].Value as int?).Value; int mapTypeInt = (resBuff[7].Value as int?).Value; int mapSourceInt = (resBuff[8].Value as int?).Value; MapType mapType = (MapType)mapTypeInt; AerialRepository repository; if (mapSourceInt == 0) { repository = new BingAerialRepository(); } else { repository = new GoogleMapsAerialRepository(); } // Get the current filename using the aerial's RasterImageDef ObjectId aerialImgDefId = aerialEnt.ImageDefId; RasterImageDef aerialImgDef = tx.GetObject(aerialImgDefId, OpenMode.ForRead) as RasterImageDef; string filename = aerialImgDef.SourceFileName; // Get the image width and height int width = (int)aerialImgDef.Size.X; int height = (int)aerialImgDef.Size.Y; // Get the request details for the image downlaod AerialImageData imageData = new AerialImageData(center, neCorner, swCorner, width, height, zoom, mapType, filename); string requestUrl = repository.BuildImageRequestUrl(imageData, update: true); // Delete the current entity aerialImgDef.UpgradeOpen(); aerialImgDef.Unload(true); // Download the new aerial photo to replace the old AerialRepository.DownloadImage(requestUrl, filename); // Reload the image entity aerialImgDef.Load(); // Commit the transaction tx.Commit(); } catch (Exception ex) { ed.WriteMessage("Error updating aerial: " + ex.Message + '\n'); ed.WriteMessage("Please try again.\n"); } finally { tx.Dispose(); } } }
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 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; }