static public Texture LoadFromFile(string filePath)
        {
            ImageImporter importer = new ImageImporter();
            ImageExporter exporter = new ImageExporter();
            Image         image;

            image = importer.LoadImage(filePath);

            if (Path.GetExtension(filePath) != ".tga" && Path.GetExtension(filePath) != ".png")
            {
                if (!File.Exists(filePath.Replace(Path.GetExtension(filePath), ".tga")))
                {
                    exporter.SaveImage(image, ImageType.Tga, filePath.Replace(Path.GetExtension(filePath), ".tga"));
                }
                image = importer.LoadImage(filePath.Replace(Path.GetExtension(filePath), ".tga"));
            }

            //image.Bind();
            //var info = DevIL.Unmanaged.IL.GetImageInfo();
            //var bitmap = new System.Drawing.Bitmap(info.Width, info.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            //var rect = new System.Drawing.Rectangle(0, 0, info.Width, info.Height);
            //var data = bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            //DevIL.Unmanaged.IL.CopyPixels(0, 0, 0, info.Width, info.Height, info.Depth, DataFormat.BGRA, DataType.UnsignedByte);
            //bitmap.UnlockBits(data);
            //var converter = new System.Drawing.ImageConverter();
            //var test = converter.ConvertTo(bitmap, typeof(byte[]));
            //var raw = (byte[])converter.ConvertTo(bitmap, typeof(byte[]));
            return(new Texture(image));
        }
        /// <summary>
        /// Runs the actual exporter
        /// </summary>
        /// <param name="settings">Export settings</param>
        private void RunExport(ImageExportSettings settings)
        {
            ICollection <Sector> sectors = General.Map.Map.SelectedSectorsCount == 0 ? General.Map.Map.Sectors : General.Map.Map.GetSelectedSectors(true);

            ImageExporter exporter = new ImageExporter(sectors, settings, AddProgress, ShowPhase, CheckCancelExport);

            try
            {
                exporter.Export();
            }
            catch (ArgumentException)             // Happens if there's not enough consecutive memory to create the file
            {
                StopExport(ImageExportResult.OutOfMemory);
                return;
            }
            catch (ImageExportCanceledException)
            {
                StopExport(ImageExportResult.Canceled);
                return;
            }
            catch (ImageExportImageTooBigException)
            {
                StopExport(ImageExportResult.ImageTooBig);
                return;
            }

            StopExport(ImageExportResult.OK);
        }
示例#3
0
        static void Main(string[] args)
        {
            // For this application to work you will need a trial license.
            // The MyAppKeyPair.snk linked in the project is not present in the repository,
            // you should generate your own strong name key and keep it private.
            //
            // 1) You can generate a strong name key with the following command in the Visual Studio command prompt:
            //     sn -k MyKeyPair.snk
            //
            // 2) The next step is to extract the public key file from the strong name key (which is a key pair):
            //     sn -p MyKeyPair.snk MyPublicKey.snk
            //
            // 3) Display the public key token for the public key:
            //     sn -t MyPublicKey.snk
            //
            // 4) Go to the project properties Singing tab, and check the "Sign the assembly" checkbox,
            //    and choose the strong name key you created.
            //
            // 5) Register and get your trial license from https://www.woutware.com/SoftwareLicenses.
            //    Enter your strong name key public key token that you got at step 3.
            WW.WWLicense.SetLicense("<license string>");

            CreateAndWriteCadDrawing();
            var model  = CadReader.Read(@"test.dwg");
            var bitmap = ImageExporter.CreateAutoSizedBitmap <Bgra32>(model, Matrix4D.Identity, GraphicsConfig.AcadLikeWithBlackBackground, new Size(600, 500));

            using (Stream stream = File.Create(@"test.png")) {
                bitmap.SaveAsPng(stream);
            }

            Console.WriteLine("Press enter.");
            Console.ReadLine();
        }
示例#4
0
        private static Image <Bgra32> RenderToBitmap(DxfModel model)
        {
            var graphicsConfig = (GraphicsConfig)GraphicsConfig.AcadLikeWithWhiteBackground.Clone();

            BoundsCalculator boundsCalculator = new BoundsCalculator();

            boundsCalculator.GetBounds(model);
            Bounds3D bounds = boundsCalculator.Bounds;

            int      size      = 2000;
            Matrix4D transform = DxfUtil.GetScaleTransform(
                bounds.Min,
                bounds.Max,
                bounds.Center,
                new Point3D(0, size, 0),
                new Point3D(size, 0, 0),
                new Point3D(0.5d * size, 0.5d * size, 0)
                );

            Memory <Bgra32> memory = new Memory <Bgra32>();

            Image.WrapMemory <Bgra32>(memory, 10, 10);
            Image <Bgra32> bitmap = ImageExporter.CreateBitmap <Bgra32>(
                model, transform,
                graphicsConfig,
                //new GraphicsOptions(false),
                new Size(size, size));

            return(bitmap);
        }
        public ClipboardItem CreateKeyImageItem(IPresentationImage image, bool ownReference = false)
        {
            Rectangle clientRectangle = image.ClientRectangle;

            if (clientRectangle.IsEmpty)
            {
                clientRectangle = new Rectangle(new Point(), image.SceneSize);
            }

            // Must build description from the source image because the ParentDisplaySet info is lost in the cloned image.
            var name        = BuildClipboardItemName(image);
            var description = BuildClipboardItemDescription(image);

            image = !ownReference?ImageExporter.ClonePresentationImage(image) : image;

            var iconGetter = new Func <ClipboardItem, Image>(item =>
            {
                _creatingItemHasChanges = item.HasChanges();
                try
                {
                    return(CreateIcon((IPresentationImage)item.Item, clientRectangle));
                }
                finally
                {
                    _creatingItemHasChanges = false;
                }
            });

            return(new ClipboardItem(image, name, description, clientRectangle, iconGetter));
        }
示例#6
0
        public void ExporteerButtonClick()
        {
            ArrayList[] selectedColums = mainController.resultController.getResultSelection(mainController.resultView.dataView);
            if (selectedColums[1].Count > 1)
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "Image (*.jpg)|*.jpg|PDF (*.pdf)|*.pdf";
                if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string extension = System.IO.Path.GetExtension(sfd.FileName);
                    Bitmap bmp       = new Bitmap(mainController.statisticView.Width, mainController.statisticView.Height);
                    mainController.statisticView.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
                    switch (extension)
                    {
                    case ".pdf":
                        ImageExporter.ExportPdf(bmp, sfd.FileName);
                        break;

                    case ".jpg":
                        ImageExporter.ExportImage(bmp, sfd.FileName);
                        ImageExporter.ExportImage(bmp, sfd.FileName);
                        break;
                    }
                }
            }
        }
示例#7
0
        public void ExportAsImageImpl(ConceptUsecase useCase)
        {
            var currentDisplay = useCase.GetCurrentDisplay();

            if (currentDisplay != null && currentDisplay.Data != null)
            {
                var saveFileDialog = new FileDialogMemento {
                    DefaultExt = "png",
                    Filter     = "PNG-Image|*.png|All Files|*.*",
                };

                if (useCase.FileDialogShow(saveFileDialog, false) == DialogResult.Ok)
                {
                    var image =
                        new ImageExporter(currentDisplay.Data, currentDisplay.Layout)
                    {
                        StyleSheet = currentDisplay.StyleSheet
                    }
                    .ExportImage();
                    if (image != null)
                    {
                        image.Save(saveFileDialog.FileName, ImageFileType.Png);
                        image.Dispose();
                    }
                }
            }
        }
示例#8
0
        //Get Jpeg from selected Layers
        public Stream GetPictures(Stream input)
        {
            string body = new StreamReader(input).ReadToEnd();
            NameValueCollection _nvc    = HttpUtility.ParseQueryString(body);
            string   _boothOutlineLayer = _nvc["BoothOutline"];
            string   _boothNumberLayer  = _nvc["BoothNumber"];
            string   _fileName          = _nvc["FileName"];
            string   _client_id         = _nvc["ClientId"];
            string   _show_id           = _nvc["ShowId"];
            string   _accessKey         = @_nvc["AccessKey"];
            string   _secretKey         = @_nvc["SecretKey"];
            string   _bucketName        = @_nvc["BucketName"];
            DxfModel _model             = ReadDxf("h://dxf_uploads//" + _client_id + " // " + _show_id + "//" + _fileName);

            foreach (DxfLayer _layer in _model.Layers)
            {
                if (_layer.Name != _boothOutlineLayer && _layer.Name != _boothNumberLayer)
                {
                    _layer.Enabled = false;
                }
            }
            string outfile = Path.GetFileNameWithoutExtension(Path.GetFullPath(_fileName));
            Stream stream;

            GDIGraphics3D graphics = new GDIGraphics3D(GraphicsConfig.BlackBackgroundCorrectForBackColor);
            Size          maxSize  = new Size(750, 750);
            Bitmap        bitmap   =
                ImageExporter.CreateAutoSizedBitmap(
                    _model,
                    graphics,
                    Matrix4D.Identity,
                    System.Drawing.Color.Black,
                    maxSize
                    );
            string fileNameS3 = outfile + ".jpg";
            string filePath   = "h://dxf_uploads//" + _client_id + " // " + _show_id + "//" + fileNameS3;

            stream = File.Create(filePath);
            ImageExporter.EncodeImageToJpeg(bitmap, stream);

            string                      _subDirectory    = _client_id + @"/" + _show_id + @"/dxf";
            AmazonS3Transfer            amazonS3Transfer = new AmazonS3Transfer();
            bool                        uploadStatus     = amazonS3Transfer.sendMyFileToS3(stream, _bucketName, _subDirectory, fileNameS3, _accessKey, _secretKey);
            Dictionary <string, string> status           = new Dictionary <string, string>();

            if (uploadStatus == true)
            {
                status.Add("status_code", "1");
            }
            else
            {
                status.Add("status_code", "0");
            }
            string result = JsonConvert.SerializeObject(status);

            WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
            return(new MemoryStream(Encoding.UTF8.GetBytes(result)));
        }
示例#9
0
        public PrintDocument CreatePrintDocument(IGraphScene <IVisual, IVisualEdge> scene, IGraphSceneLayout <IVisual, IVisualEdge> layout)
        {
            this.painter = new ImageExporter(scene, layout);

            painter.Viewport.ClipOrigin = scene.Shape.Location;

            var doc = new PrintDocument();

            doc.PrintPage += new PrintPageEventHandler(doc_PrintPage);
            return(doc);
        }
示例#10
0
        private void screenshotButton_Click(object sender, EventArgs e)
        {
            Bitmap         bitmap         = ImageExporter.FromBundle(new Bundle(this.graphVisualizationInfoView.Controller.Model.Paintables), this.graphVisualizationInfoView.Controller.View.Graphics);
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Title        = "Save Screenshot";
            saveFileDialog.DefaultExt   = "png";
            saveFileDialog.Filter       = "Portable Network Graphics|*.png|All Files|*.*";
            saveFileDialog.FilterIndex  = 1;
            saveFileDialog.AddExtension = true;

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                bitmap.Save(saveFileDialog.FileName);
            }
        }
示例#11
0
        public static QuickRouteJpegExtensionData FromImageExporter(ImageExporter exporter)
        {
            var data = new QuickRouteJpegExtensionData
            {
                Version = currentVersion,
                ImageCornerPositions =
                    exporter.Document.GetImageCornersLongLat(exporter.ImageBounds, exporter.MapBounds,
                                                             exporter.Properties.PercentualSize),
                MapCornerPositions         = exporter.Document.GetMapCornersLongLat(),
                MapLocationAndSizeInPixels = exporter.MapBounds,
                Sessions       = exporter.Sessions,
                PercentualSize = exporter.Properties.PercentualSize
            };

            return(data);
        }
示例#12
0
        } // End Sub Main

        // SaveAImage(model, @"test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
        public static void SaveAImage(DxfModel model, string path, System.Drawing.Imaging.ImageFormat fmt)
        {
            // Convert the CAD drawing to a bitmap.
            System.Drawing.Bitmap bitmap = ImageExporter.CreateAutoSizedBitmap(
                model,
                Matrix4D.Identity,
                GraphicsConfig.WhiteBackgroundCorrectForBackColor,
                System.Drawing.Drawing2D.SmoothingMode.HighQuality,
                new System.Drawing.Size(500, 400)
                );

            // Send the bitmap to the client.
            // context.Response.ContentType = "image/jpeg";
            // bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            bitmap.Save(path, fmt);
        } // End Sub SaveAImage
示例#13
0
        /// <summary>
        /// 所有要打印的图像都保存在这个<see cref="DisplaySet"/>中
        /// </summary>

        public static void AddPresentationImage(IPresentationImage presentationImage)
        {
            if (presentationImage == null)
            {
                return;
            }
            var clonPi = ImageExporter.ClonePresentationImage(presentationImage);

            if (clonPi != null)
            {
                PresentationImage image = clonPi as PresentationImage;
                if (_imageViewerComponent != null)
                {
                    _imageViewerComponent.DisplaySet.PresentationImages.Add(image);
                    image.Selected = false;
                }
            }
        }
示例#14
0
        /// <summary>
        /// Called to create a clipboard item representing a presentation image.
        /// </summary>
        /// <param name="image"></param>
        /// <param name="ownReference"></param>
        /// <returns></returns>
        public virtual ClipboardItem CreatePresentationImageItem(IPresentationImage image, bool ownReference = false)
        {
            Rectangle clientRectangle = image.ClientRectangle;

            if (clientRectangle.IsEmpty)
            {
                clientRectangle = new Rectangle(new Point(), image.SceneSize);
            }

            // Must build description from the source image because the ParentDisplaySet info is lost in the cloned image.
            var name        = BuildClipboardItemName(image);
            var description = BuildClipboardItemDescription(image);

            image = !ownReference?ImageExporter.ClonePresentationImage(image) : image;

            var bmp = CreateIcon(image, clientRectangle);

            return(new ClipboardItem(image, bmp, name, description, clientRectangle));
        }
        public void PrintPreviewPaste()
        {
            var imageBox = this.ImageViewer.SelectedImageBox;

            if (imageBox == null || imageBox.DisplaySet == null || imageBox.SelectedTile == null || selectPresentationImages == null)
            {
                return;
            }

            var memorableCommand = new MemorableUndoableCommand(imageBox)
            {
                BeginState = CreateMemento()
            };

            if (this.Context.Viewer.SelectedPresentationImage == null)
            {
                foreach (var selectPresentationImage in selectPresentationImages)
                {
                    imageBox.DisplaySet.PresentationImages.Add(ImageExporter.ClonePresentationImage(selectPresentationImage));
                }
            }
            else
            {
                int index = imageBox.DisplaySet.PresentationImages.IndexOf(this.Context.Viewer.SelectedPresentationImage);

                for (int i = selectPresentationImages.Count - 1; i >= 0; i--)
                {
                    imageBox.DisplaySet.PresentationImages.Insert(index, ImageExporter.ClonePresentationImage(selectPresentationImages[i]));
                }
            }
            imageBox.TopLeftPresentationImageIndex = imageBox.TopLeftPresentationImageIndex;
            imageBox.Draw();
            imageBox.SelectDefaultTile();
            memorableCommand.EndState = CreateMemento();
            var historyCommand = new DrawableUndoableCommand(imageBox)
            {
                Name = SR.CommandPrintPreviewPaste
            };

            historyCommand.Enqueue(memorableCommand);
            this.Context.Viewer.CommandHistory.AddCommand(historyCommand);
            PropertyChanged();
        }
示例#16
0
        /// <summary>
        /// Export to an image format
        /// </summary>
        public static void Export(GraphicVisual visual, int width, bool addMargin, out string message)
        {
            message = string.Empty;
            var saveDialog = new Microsoft.Win32.SaveFileDialog();

            saveDialog.Filter = "ICO File (*.ico)|*.ico|SVG File (*.svg)|*.svg|SVGZ File (*.svgz)|*.svgz|PNG File (*.png)|*.png|JPG File (*.jpg)|*.jpg|TIFF File (*.tiff)|*.tiff|BMP File (*.bmp)|*.bmp|GIF File (*.gif)|*.gif|EPS File (*.eps)|*.eps";

            var result = saveDialog.ShowDialog();

            if (result == false)
            {
                return;
            }

            var fileExtension = Path.GetExtension(saveDialog.FileName).ToLower();

            switch (fileExtension)
            {
            case ".svg":
                SvgExporter.ExportSvg(visual, width, saveDialog.FileName);
                break;

            case ".svgz":
                SvgExporter.ExportSvgz(visual, width, saveDialog.FileName);
                break;

            case ".ico":
                IcoExporter.ExportIco(visual, saveDialog.FileName);
                break;

            case ".eps":
            {
                var exporter = new EpsExporter();
                exporter.Export(visual, width, saveDialog.FileName, out message);
                break;
            }

            default:
                ImageExporter.ExportImage(visual, width, addMargin, saveDialog.FileName);
                break;
            }
        }
        public void PrintPreviewCopy()
        {
            if (this.ImageViewer.SelectedImageBox == null || this.ImageViewer.SelectedImageBox.DisplaySet == null || this.Context.Viewer.SelectedPresentationImage == null)
            {
                return;
            }
            var imageBox = this.ImageViewer.SelectedImageBox;
            PrintImageViewerComponent component = this.Context.Viewer as PrintImageViewerComponent;

            if (component == null)
            {
                return;
            }

            if (selectPresentationImages == null)
            {
                selectPresentationImages = new List <IPresentationImage>();
            }
            else
            {
                selectPresentationImages.Clear();
            }

            foreach (var selectPresentationImage in component.SelectPresentationImages)
            {
                PresentationImage image = ImageExporter.ClonePresentationImage(selectPresentationImage) as PresentationImage;
                if (image == null)
                {
                    continue;
                }
                image.Selected = false;
                selectPresentationImages.Add(image);
            }

            foreach (PrintViewTile tile in imageBox.Tiles)
            {
                if (tile.PresentationImage == null)
                {
                    tile.Deselect();
                }
            }
        }
示例#18
0
        private void InitDevIL()
        {
            m_importer = new ImageImporter();
            m_exporter = new ImageExporter();
            ImageState state = new ImageState();

            state.AbsoluteFormat   = DataFormat.BGRA;
            state.AbsoluteDataType = DataType.UnsignedByte;
            state.AbsoluteOrigin   = OriginLocation.UpperLeft;
            state.Apply();

            CompressionState comp = new CompressionState();

            comp.KeepDxtcData = true;
            comp.Apply();

            SaveState sstate = new SaveState();

            sstate.OverwriteExistingFile = true;
            sstate.Apply();
        }
示例#19
0
        private void ExportToImage()
        {
            // Convert geometry selection to sectors
            General.Map.Map.ConvertSelection(SelectionType.Sectors);

            // Get sectors
            ICollection <Sector> sectors = General.Map.Map.SelectedSectorsCount == 0 ? General.Map.Map.Sectors : General.Map.Map.GetSelectedSectors(true);

            if (sectors.Count == 0)
            {
                General.Interface.DisplayStatus(StatusType.Warning, "Image export failed. Map has no sectors!");
                return;
            }

            ImageExportSettingsForm form = new ImageExportSettingsForm();

            if (form.ShowDialog() == DialogResult.OK)
            {
                ImageExportSettings settings = new ImageExportSettings(Path.GetDirectoryName(form.FilePath), Path.GetFileNameWithoutExtension(form.FilePath), Path.GetExtension(form.FilePath), form.Floor, form.Fullbright, form.Brightmap, form.Tiles, form.GetPixelFormat(), form.GetImageFormat());
                ImageExporter       exporter = new ImageExporter(sectors, settings);

                string text = "The following images will be created:\n\n" + string.Join("\n", exporter.GetImageNames());

                DialogResult result = MessageBox.Show(text, "Export to image", MessageBoxButtons.OKCancel);

                if (result == DialogResult.OK)
                {
                    try
                    {
                        exporter.Export();

                        MessageBox.Show("Export successful.", "Export to image", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (ArgumentException e)                     // Happens if there's not enough consecutive memory to create the file
                    {
                        MessageBox.Show("Exporting failed. There's likely not enough consecutive free memory to create the image. Try a lower color depth or file format", "Export failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
示例#20
0
        static public List <Texture> LoadFromFile(string rootPath, string filePath)
        {
            ImageImporter  importer = new ImageImporter();
            ImageExporter  exporter = new ImageExporter();
            Image          image;
            List <Texture> textures = new List <Texture>();

            string[] fps = filePath.Split('*');
            string   fp;

            for (int i = 0; i < fps.Length; i++)
            {
                fp    = rootPath + fps[i];
                image = importer.LoadImage(fp);

                if (Path.GetExtension(fp) != ".tga" && Path.GetExtension(fp) != ".png")
                {
                    if (!File.Exists(fp.Replace(Path.GetExtension(fp), ".tga")))
                    {
                        exporter.SaveImage(image, ImageType.Tga, fp.Replace(Path.GetExtension(fp), ".tga"));
                    }
                    image = importer.LoadImage(fp.Replace(Path.GetExtension(fp), ".tga"));
                }

                //image.Bind();
                //var info = DevIL.Unmanaged.IL.GetImageInfo();
                //var bitmap = new System.Drawing.Bitmap(info.Width, info.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                //var rect = new System.Drawing.Rectangle(0, 0, info.Width, info.Height);
                //var data = bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                //DevIL.Unmanaged.IL.CopyPixels(0, 0, 0, info.Width, info.Height, info.Depth, DataFormat.BGRA, DataType.UnsignedByte);
                //bitmap.UnlockBits(data);
                //var converter = new System.Drawing.ImageConverter();
                //var test = converter.ConvertTo(bitmap, typeof(byte[]));
                //var raw = (byte[])converter.ConvertTo(bitmap, typeof(byte[]));

                textures.Add(new Texture(image, fp));
            }
            return(textures);
        }
 private static Bitmap CreateOneUnitToOnePixelBitmap(
     DxfModel model,
     Matrix4D transform,
     GraphicsConfig graphicsConfig,
     SmoothingMode smoothingMode)
 {
     // first calculate the size of the model
     //BoundsCalculator boundsCalculator = new BoundsCalculator(graphicsConfig);
     //boundsCalculator.GetBounds(model, transform);
     //Bounds3D bounds = boundsCalculator.Bounds;
     //Vector3D delta = bounds.Delta;
     //// now determine image size from this
     //// Note: Have to add 2 extra pixels on each side, otherwise Windows will not render
     //// the graphics on the outer edges. Also there seems to be always an empty unused line
     //// around the bitmap, but that's not a problem, just a minor waste of space.
     //const int margin = 2;
     //int width = (int)System.Math.Ceiling(delta.X) + 2 * margin;
     //int height = (int)System.Math.Ceiling(delta.Y) + 2 * margin;
     //// Now move the model so it is centered in the coordinate ranges
     //// margin &lt;= x &lt;= width+margin and margin &lt;= y &lt;= height+margin
     //// Be careful: in DXF y points up, but in Bitmap it points down!
     //Matrix4D to2DTransform = DxfUtil.GetScaleTransform(
     //  bounds.Corner1,
     //  bounds.Corner2,
     //  new Point3D(bounds.Corner1.X, bounds.Corner2.Y, 0d),
     //  new Point3D(0d, delta.Y, 0d),
     //  new Point3D(delta.X, 0d, 0d),
     //  new Point3D(margin, margin, 0d)
     //) * transform;
     // now use standard method to create bitmap
     System.Drawing.Size maxSize = new System.Drawing.Size(1000, 600);
     return(ImageExporter.CreateAutoSizedBitmap(model, Matrix4D.Identity,
                                                GraphicsConfig.WhiteBackgroundCorrectForBackColor,
                                                SmoothingMode.HighQuality,
                                                maxSize));
 }
示例#22
0
        public static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                args = new string[2];
                //args[1] = "D:\\C项目\\CadLCmd\\CadLCmd\\dwg\\test1.dwg";
                //args[1] = "D:\\C项目\\CadLCmd\\CadLCmd\\dwg\\test2.dwg";
                //args[1] = "D:\\C项目\\CadLCmd\\CadLCmd\\dwg\\test3.dwg";
                //args[1] = "D:\\C项目\\CadLCmd\\CadLCmd\\dwg\\test4.dwg";
                args[1] = "D:\\C项目\\CadLCmd\\CadLCmd\\dwg\\test5Insert.dwg";
                //args[1] = "D:\\C项目\\CadLCmd\\CadLCmd\\dwg\\test6.dwg";
            }
            string format   = args[0];
            string filename = args[1];

            DxfModel model = null;

            try
            {
                string extension = Path.GetExtension(filename);
                if (string.Compare(extension, ".dwg", true) == 0)
                {
                    model = DwgReader.Read(filename);
                }
                else
                {
                    model = DxfReader.Read(filename);
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Error occurred: " + e.Message);
                Environment.Exit(1);
            }

            //foreach (var entityGroups in model.Entities.GroupBy(a => a.GetType()))
            //{

            //    Console.WriteLine(entityGroups.GetType());

            //    //if (typeof(DxfLine) == entityGroups.Key)
            //    //{
            //    //    foreach (var item in entityGroups)
            //    //    {
            //    //        Console.WriteLine(item.Color);

            //    //    }
            //    //}

            //}
            //FileStream fs = new FileStream("D:\\C项目\\CadLCmd\\CadLCmd\\txt\\test1.txt", FileMode.Create);



            FindEntities(model.Entities);



            string json = JsonConvert.SerializeObject(cadEntities);

            File.WriteAllText("D:\\C项目\\CadLCmd\\CadLCmd\\txt\\model.json", json);
            File.WriteAllText("D:\\Project\\cadtest\\node_modules\\@cadTestUbim\\res\\data\\dxfdata.json", json);

            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();

            KTCodes = ktls.ToArray();

            KTest = ktest.ToArray();

            DxfType = dxfType.ToArray();

            KInsert = kins.ToArray();

            KEC = kco.ToArray();

            KCIRCLE = kcircle.ToArray();

            //Console.ReadKey();
            string outfile = Path.GetDirectoryName(Path.GetFullPath(filename)) + "\\12";
            Stream stream;

            if (format == "pdf")
            {
                BoundsCalculator boundsCalculator = new BoundsCalculator();
                boundsCalculator.GetBounds(model);
                Bounds3D  bounds    = boundsCalculator.Bounds;
                PaperSize paperSize = PaperSizes.GetPaperSize(PaperKind.Letter);
                // Lengths in inches.
                float pageWidth  = (float)paperSize.Width / 100f;
                float pageHeight = (float)paperSize.Height / 100f;
                float margin     = 0.5f;
                // Scale and transform such that its fits max width/height
                // and the top left middle of the cad drawing will match the
                // top middle of the pdf page.
                // The transform transforms to pdf pixels.
                Matrix4D to2DTransform = DxfUtil.GetScaleTransform(
                    bounds.Corner1,
                    bounds.Corner2,
                    new Point3D(bounds.Center.X, bounds.Corner2.Y, 0d),
                    new Point3D(new Vector3D(margin, margin, 0d) * PdfExporter.InchToPixel),
                    new Point3D(new Vector3D(pageWidth - margin, pageHeight - margin, 0d) * PdfExporter.InchToPixel),
                    new Point3D(new Vector3D(pageWidth / 2d, pageHeight - margin, 0d) * PdfExporter.InchToPixel)
                    );
                using (stream = File.Create(outfile + ".pdf"))
                {
                    PdfExporter pdfGraphics = new PdfExporter(stream);
                    pdfGraphics.DrawPage(
                        model,
                        GraphicsConfig.WhiteBackgroundCorrectForBackColor,
                        to2DTransform,
                        paperSize
                        );
                    pdfGraphics.EndDocument();
                }
            }
            else
            {
                GDIGraphics3D graphics = new GDIGraphics3D(GraphicsConfig.BlackBackgroundCorrectForBackColor);
                Size          maxSize  = new Size(500, 500);
                Bitmap        bitmap   =
                    ImageExporter.CreateAutoSizedBitmap(
                        model,
                        graphics,
                        Matrix4D.Identity,
                        System.Drawing.Color.Black,
                        maxSize
                        );
                switch (format)
                {
                case "bmp":
                    using (stream = File.Create(outfile + ".bmp"))
                    {
                        ImageExporter.EncodeImageToBmp(bitmap, stream);
                    }
                    break;

                case "gif":
                    using (stream = File.Create(outfile + ".gif"))
                    {
                        ImageExporter.EncodeImageToGif(bitmap, stream);
                    }
                    break;

                case "tiff":
                    using (stream = File.Create(outfile + ".tiff"))
                    {
                        ImageExporter.EncodeImageToTiff(bitmap, stream);
                    }
                    break;

                case "png":
                    using (stream = File.Create(outfile + ".png"))
                    {
                        ImageExporter.EncodeImageToPng(bitmap, stream);
                    }
                    break;

                case "jpg":
                    using (stream = File.Create(outfile + ".jpg"))
                    {
                        ImageExporter.EncodeImageToJpeg(bitmap, stream);
                    }
                    break;

                default:
                    Console.WriteLine("Unknown format " + format + ".");
                    break;
                }
            }
        }
示例#23
0
        public MainForm( )
        {
            InitializeComponent( );
            cameraFpsLabel.Text = string.Empty;
            permittedCodesLabel.Text = string.Empty;

            // initialise filters
            grayFilter = new AForge.Imaging.Filters.Grayscale(0.2125, 0.7154, 0.0721);
            otsuFilter = new AForge.Imaging.Filters.OtsuThreshold();

            // image buffers
            grayBuffer = new Bitmap(DesiredWidth, DesiredHeight, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);

            // component finder
            componentFinder = new ComponentFinder();

            // rag constructor
            regionAdjacencyGraph = new RegionAdjacencyGraph(DesiredWidth, DesiredHeight);

            // Marker Detector
            markerDetector = new MarkerDetector();

            // Worker
            resetEvent = new ManualResetEvent(false);
            frameMutex = new Mutex(false);   //RNM

            // Image exporter
            imageExporter = new ImageExporter(this.ExportImage);
            openFileDialog = new SaveFileDialog();
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
            openFileDialog.Filter = "Bitmap Images|*.bmp|JPEG Images|*.jpg|PNG Images|*.png|All Files|*.*";

            // Probability maps
            probabilityMap = null;

            //xml
            markerStreamProducer = new MakerStreamProducer(PORT);
            markerStreamProducer.Start();
            xmlDocument = new XmlDocument();
            xmlDocument.LoadXml("<!DOCTYPE CERAMICS [<!ELEMENT STREAMS (STREAM+)><!ELEMENT STREAM (MARKER+)><!ELEMENT MARKER (EMPTY)><!ATTLIST STREAM DATE CDATA #REQUIRED><!ATTLIST STREAM ID CDATA #REQUIRED><!ATTLIST MARKER CODE CDATA #REQUIRED><!ATTLIST MARKER TIMESTAMP CDATA #REQUIRED><!ATTLIST MARKER X1 CDATA #REQUIRED><!ATTLIST MARKER Y1 CDATA #REQUIRED><!ATTLIST MARKER X2 CDATA #REQUIRED><!ATTLIST MARKER Y2 CDATA #REQUIRED>]><stream></stream>");

            XmlElement root = xmlDocument.DocumentElement;
            root.SetAttribute("date",DateTime.Now.Date.ToString().Substring(0,10));
            root.SetAttribute("id", "0001");

            Console.WriteLine(xmlDocument.OuterXml);

            xmlDocument.Save(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\dtd.xml");

            displayDeviceList();
        }
示例#24
0
        void ExportWorker_RunWorkerCompleted(object i_sender, RunWorkerCompletedEventArgs i_e)
        {
            if (m_export_cancelled)
                return;

            btnPlay.IsEnabled = true;
            preferencesMenu.IsEnabled = true;
            progressCircular.Visibility = Visibility.Hidden;
            long totalImages = m_exporter.GetExportingResult();
            string message = string.Empty;

            if (totalImages > 0)
            {
                message = String.Format("Exported {0} screenshots successfully.\nWould you like to delete the original screenshots?", totalImages);
                MessageBoxResult result = MessageBox.Show(message, "Export result", MessageBoxButton.YesNo, MessageBoxImage.Information);

                if (result == MessageBoxResult.Yes)
                {
                    m_exporter.DeleteAllImages();
                }
                Process.Start("explorer.exe", m_exporter.GetRootDirectory());
            }
            else
                MessageBox.Show("No screenshots were exported.");

            //Clean up resources
            btnExport.IsEnabled = true;
            m_exporter_worker.DoWork -= worker_DoWork;
            m_exporter_worker.RunWorkerCompleted -= ExportWorker_RunWorkerCompleted;
            m_exporter_worker.Dispose();
            m_exporter = null;
            CancelLink.Visibility = System.Windows.Visibility.Hidden;
            trayIcon.Icon = m_app_not_running;
        }
示例#25
0
        private void Export()
        {
            SnapshotSettings snapSettings = SettingsManager.Instance.GetSnapshotSettings();
            System.Windows.Forms.FolderBrowserDialog browser = new System.Windows.Forms.FolderBrowserDialog();
            string subDirectory = snapSettings.GetCurrentSubdirectory();
            string parentDirectory = snapSettings.GetParentDirectory();

            //Initialise browser folder for easier navigation
            browser.SelectedPath = parentDirectory;

            browser.Description = "Choose directory for exporting";
            System.Windows.Forms.DialogResult result = browser.ShowDialog();

            if (result != System.Windows.Forms.DialogResult.OK)
                return;

            m_exporter = new ImageExporter();
            m_exporter.SetRootDirectory(browser.SelectedPath);
            if (!m_exporter.CanExport())
            {
                MessageBox.Show("There are no screenshots to export.\nExporting stopped.");
                return;
            }

            btnPlay.IsEnabled = false;
            btnStop.IsEnabled = false;
            preferencesMenu.IsEnabled = false;

            progressCircular.Visibility = Visibility.Visible;
            CancelLink.Visibility = System.Windows.Visibility.Visible;
            trayIcon.Icon = m_app_exporting;

            m_exporter_worker.DoWork += worker_DoWork;
            m_exporter_worker.RunWorkerCompleted += ExportWorker_RunWorkerCompleted;

            if (!m_exporter_worker.IsBusy)
                m_exporter_worker.RunWorkerAsync();

            browser.Dispose();
            btnExport.IsEnabled = false;
        }
示例#26
0
        /// <summary>
        /// Exports all textures to the directory specified.
        /// </summary>
        /// <param name="dir">Directory where all textures should be extracted.</param>
        /// <param name="mode">Mode of extraction. Range: ".dds", ".png", ".jpg", ".tiff", ".bmp".</param>
        /// <returns>True if export was successful.</returns>
        public override bool ExportTextures(string dir, string mode)
        {
            ImageType type;

            switch (mode)
            {
            case ".dds":
                type = ImageType.Dds;
                break;

            case ".png":
                type = ImageType.Png;
                break;

            case ".jpg":
                type = ImageType.Jpg;
                break;

            case ".tiff":
                type = ImageType.Tiff;
                break;

            case ".bmp":
                type = ImageType.Bmp;
                break;

            default:
                if (Process.MessageShow)
                {
                    MessageBox.Show("Export mode provided is not supported.", "Warning");
                }
                else
                {
                    Console.WriteLine("Export mode provided is not supported.");
                }
                return(false);
            }

            if (!Directory.Exists(dir))
            {
                if (Process.MessageShow)
                {
                    MessageBox.Show("Directory provided does not exist.", "Warning");
                }
                else
                {
                    Console.WriteLine("Directory provided does not exist.");
                }
                return(false);
            }

            try
            {
                foreach (var tpk in this.TPKBlocks.Collections)
                {
                    string tpkdir = tpk.CollectionName.Substring(2, tpk.CollectionName.Length - 2);
                    tpkdir = Path.Combine(dir, tpkdir);
                    if (!Directory.Exists(tpkdir))
                    {
                        Directory.CreateDirectory(tpkdir);
                    }
                    foreach (var tex in tpk.Textures)
                    {
                        string texdir = Path.Combine(tpkdir, tex.CollectionName);
                        texdir += mode;
                        var data = tex.GetDDSArray();
                        if (mode == ".dds")
                        {
                            using (var bw = new BinaryWriter(File.Open(texdir, FileMode.Create)))
                            {
                                bw.Write(data);
                            }
                        }
                        else
                        {
                            using (var sr = new MemoryStream(data))
                                using (var im = new ImageImporter())
                                    using (var ex = new ImageExporter())
                                    {
                                        using (var image = im.LoadImageFromStream(sr))
                                        {
                                            ex.SaveImage(image, type, texdir);
                                        }
                                    }
                        }
                    }
                }
                return(true);
            }
            catch (Exception e)
            {
                if (Process.MessageShow)
                {
                    MessageBox.Show(e.Message, "Warning");
                }
                else
                {
                    Console.WriteLine($"{e.Message}");
                }
                return(false);
            }
        }
示例#27
0
 private Bitmap GenerateShadedMap(HeightData data, Bitmap surface)
 {
     return(ImageExporter.GenerateCompositeMap(data, surface, 0.3f, 0.3f));
 }
示例#28
0
 private static IPresentationImage ClonePresentationImage(IPresentationImage presentationImage)
 {
     return(ImageExporter.ClonePresentationImage(presentationImage));
 }
        protected override void Process()
        {
            SBLicenseManager.TElSBLicenseManager m = new SBLicenseManager.TElSBLicenseManager();
            m.LicenseKey = "8F1317CD48AC4E68BABA5E339D8B365414D7ADA0289CA037E9074D29AD95FF3EC5D796BEFF0FBADB3BD82F48644C9EB810D9B5A305E0D2A1885C874D8BF974B9608CE918113FBE2AA5EEF8264C93B25ABEA98715DB4AD265F47CE02FC9952D69F2C3530B6ABAAA4C43B45E7EF6A8A0646DA038E34FBFB629C2BF0E83C6B348726E622EBD52CA05CF74C68F1279849CCD0C13EA673916BA42684015D658B8E7626F15BD826A4340EDB36CE55791A051FDBCF9FA1456C3B5008AD9990A0185C0EA3B19F9938CB7DA1FE82736ED4C7A566D4BFD53411E8380F4B020CB50E762520EFAE190836FD253B00DB18D4A485C7DC918AA4DCEC856331DD231CC8DC9C741C3";


            using (var unit = GetUnitOfWork())
            {
                foreach (Connector connector in base.Connectors.Where(c => ((ConnectorType)c.ConnectorType).Has(ConnectorType.WebAssortment)))
                {
#if DEBUG
                    if (connector.ConnectorID != 6)
                    {
                        continue;
                    }
#endif
                    string singleProduct = string.Empty;
                    try
                    {
                        log.DebugFormat("Start Magento Image Synchronization for {0}", connector.Name);


                        if (connector.ConnectorSystemType == null)
                        {
                            log.AuditError(string.Format("No Connector System Settings found for {0}, Magento Export can not be executed!", connector.Name), "Magento Export");
                            continue;
                        }

                        var type = GetType().ToString();

                        string serializationPath = @"C:\Magento";//default
                        var    config            = GetConfiguration();
                        if (config.AppSettings.Settings["AssortmentSerializationPath"] != null)
                        {
                            serializationPath = config.AppSettings.Settings["AssortmentSerializationPath"].Value;
                        }

                        var connectorSerializationPath = serializationPath;
                        if (!Directory.Exists(connectorSerializationPath))
                        {
                            Directory.CreateDirectory(connectorSerializationPath);
                        }

//#if DEBUG
//            connector.Connection = "server=127.0.0.1;User Id=root;password=Om3Aih7aohQu9uPeahP4Ul3p;database=coolcat;Connect Timeout=30000;Default Command Timeout=30000;port=6014";
//#endif
                        ImageExporter imageExporter = new ImageExporter(connector, log, GetConfiguration(), connectorSerializationPath);

                        imageExporter.Execute();
                    }
                    catch (Exception ex)
                    {
                        log.Error("Error in Magento Plugin", ex);
                    }

                    var triggerIndex = connector.ConnectorSettings.GetValueByKey <bool>("ImageTriggerIndexing", false);

                    if (triggerIndex)
                    {
                        log.Info("Will place trigger for indexing");
                        try
                        {
                            var info = SftpHelper.GetFtpTriggerIndexInfo(connector);

                            IndexerHelper hlp = new IndexerHelper(info, "cache");
                            hlp.CreateImageTrigger();

                            log.Info("Placed a trigger file");
                        }
                        catch (Exception e)
                        {
                            log.AuditError("Couldnt upload a trigger file", e, "Magento export");
                        }
                    }

                    log.DebugFormat("Finished Magento Image Synchronization For {0}", connector.Name);
                }
            }
        }
        public void getDXFFormat(DxfModel model, string filename, string outfile)
        {
            try
            {
                string extension = System.IO.Path.GetExtension(filename);
                if (string.Compare(extension, ".dwg", true) == 0)
                {
                    model = DwgReader.Read(filename);
                }
                else
                {
                    model = DxfReader.Read(filename);
                }
            }
            catch (Exception e)
            {
                //Console.Error.WriteLine("Error occurred: " + e.Message);
                //Environment.Exit(1);
            }

            GDIGraphics3D graphics = new GDIGraphics3D(GraphicsConfig.BlackBackgroundCorrectForBackColor);
            Size          maxSize  = new Size(500, 500);
            Bitmap        bitmap   =
                ImageExporter.CreateAutoSizedBitmap(
                    model,
                    graphics,
                    Matrix4D.Identity,
                    System.Drawing.Color.Black,
                    maxSize
                    );
            //string outfile = Path.GetFileNameWithoutExtension(Path.GetFullPath(filename));
            Stream stream = null;
            //string outfile = AppDomain.CurrentDomain.BaseDirectory + "Drill\\rockHistogram\\"+filename;

            BoundsCalculator boundsCalculator = new BoundsCalculator();

            boundsCalculator.GetBounds(model);
            Bounds3D  bounds    = boundsCalculator.Bounds;
            PaperSize paperSize = PaperSizes.GetPaperSize(PaperKind.A4);//设置为A4纸的大小
            // Lengths in inches.
            float pageWidth  = (float)paperSize.Width / 100f;
            float pageHeight = (float)paperSize.Height / 100f;
            float margin     = 0.2f; //值越小 model相对于pdf图幅越大
            // Scale and transform such that its fits max width/height
            // and the top left middle of the cad drawing will match the
            // top middle of the pdf page.
            // The transform transforms to pdf pixels.
            Matrix4D to2DTransform = DxfUtil.GetScaleTransform(
                bounds.Corner1,
                bounds.Corner2,
                new Point3D(bounds.Center.X, bounds.Corner2.Y, 0d),
                new Point3D(new Vector3D(margin, margin, 0d) * PdfExporter.InchToPixel),
                new Point3D(new Vector3D(pageWidth - margin, pageHeight - margin, 0d) * PdfExporter.InchToPixel),
                new Point3D(new Vector3D(pageWidth / 2d, pageHeight - margin, 0d) * PdfExporter.InchToPixel)
                );

            using (stream = File.Create(outfile + ".pdf"))
            {
                PdfExporter pdfGraphics = new PdfExporter(stream);
                pdfGraphics.DrawPage(
                    model,
                    GraphicsConfig.WhiteBackgroundCorrectForBackColor,
                    to2DTransform,
                    paperSize
                    );
                pdfGraphics.EndDocument();
            }

            /*
             * 可选的图片格式
             * stream = File.Create(outfile + ".png");
             * ImageExporter.EncodeImageToPng(bitmap, stream);
             *
             * stream = File.Create(outfile + ".tiff");
             * ImageExporter.EncodeImageToTiff(bitmap, stream);
             *
             * stream = File.Create(outfile + ".jpg");
             * ImageExporter.EncodeImageToJpeg(bitmap, stream);
             *
             * stream = File.Create(outfile + ".gif");
             * ImageExporter.EncodeImageToGif(bitmap, stream);
             *
             * stream = File.Create(outfile + ".bmp");
             * ImageExporter.EncodeImageToBmp(bitmap, stream);
             */
        }
示例#31
0
        public void ExportModelToDirectoryWithExportOptions(Model model, String directory, ExportOptions exportOptions)
        {
            //TODO: Figure out what to do with non-version 4 models.
            if (model != null && model.Version != 4)
            {
                return;
            }

            NumberFormatInfo format = new NumberFormatInfo();

            format.NumberDecimalSeparator = ".";

            if (exportOptions.Package)
            {
                try
                {
                    DirectoryInfo directoryInfo = Directory.CreateDirectory(directory + @"\" + Path.GetFileNameWithoutExtension(model.Name));
                    directory = directoryInfo.FullName;
                }
                catch (Exception) { }
            }

            if (exportOptions.Textures)
            {
                ImageImporter imageImporter = new ImageImporter();
                ImageExporter imageExporter = new ImageExporter();

                foreach (String textureString in model.TextureStrings)
                {
                    MemoryStream textureMemoryStream = AssetManager.Instance.CreateAssetMemoryStreamByName(textureString);

                    if (textureMemoryStream == null)
                    {
                        continue;
                    }

                    Image textureImage = imageImporter.LoadImageFromStream(textureMemoryStream);

                    if (textureImage == null)
                    {
                        continue;
                    }

                    imageExporter.SaveImage(textureImage, exportOptions.TextureFormat.ImageType, directory + @"\" + Path.GetFileNameWithoutExtension(textureString) + @"." + exportOptions.TextureFormat.Extension);
                }
            }

            String path = directory + @"\" + Path.GetFileNameWithoutExtension(model.Name) + ".obj";

            FileStream   fileStream   = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Write);
            StreamWriter streamWriter = new StreamWriter(fileStream);

            for (Int32 i = 0; i < model.Meshes.Length; ++i)
            {
                Mesh mesh = model.Meshes[i];

                MaterialDefinition materialDefinition = MaterialDefinitionManager.Instance.MaterialDefinitions[model.Materials[(Int32)mesh.MaterialIndex].MaterialDefinitionHash];
                VertexLayout       vertexLayout       = MaterialDefinitionManager.Instance.VertexLayouts[materialDefinition.DrawStyles[0].VertexLayoutNameHash];

                //position
                VertexLayout.Entry.DataTypes positionDataType;
                Int32 positionOffset;
                Int32 positionStreamIndex;

                vertexLayout.GetEntryInfoFromDataUsageAndUsageIndex(VertexLayout.Entry.DataUsages.Position, 0, out positionDataType, out positionStreamIndex, out positionOffset);

                Mesh.VertexStream positionStream = mesh.VertexStreams[positionStreamIndex];

                for (Int32 j = 0; j < mesh.VertexCount; ++j)
                {
                    Vector3 position = readVector3(exportOptions, positionOffset, positionStream, j);

                    position.X *= exportOptions.Scale.X;
                    position.Y *= exportOptions.Scale.Y;
                    position.Z *= exportOptions.Scale.Z;

                    streamWriter.WriteLine("v " + position.X.ToString(format) + " " + position.Y.ToString(format) + " " + position.Z.ToString(format));
                }

                //texture coordinates
                if (exportOptions.TextureCoordinates)
                {
                    VertexLayout.Entry.DataTypes texCoord0DataType;
                    Int32 texCoord0Offset      = 0;
                    Int32 texCoord0StreamIndex = 0;

                    Boolean texCoord0Present = vertexLayout.GetEntryInfoFromDataUsageAndUsageIndex(VertexLayout.Entry.DataUsages.Texcoord, 0, out texCoord0DataType, out texCoord0StreamIndex, out texCoord0Offset);

                    if (texCoord0Present)
                    {
                        Mesh.VertexStream texCoord0Stream = mesh.VertexStreams[texCoord0StreamIndex];

                        for (Int32 j = 0; j < mesh.VertexCount; ++j)
                        {
                            Vector2 texCoord;

                            switch (texCoord0DataType)
                            {
                            case VertexLayout.Entry.DataTypes.Float2:
                                texCoord.X = BitConverter.ToSingle(texCoord0Stream.Data, (j * texCoord0Stream.BytesPerVertex) + 0);
                                texCoord.Y = 1.0f - BitConverter.ToSingle(texCoord0Stream.Data, (j * texCoord0Stream.BytesPerVertex) + 4);
                                break;

                            case VertexLayout.Entry.DataTypes.float16_2:
                                texCoord.X = Half.FromBytes(texCoord0Stream.Data, (j * texCoord0Stream.BytesPerVertex) + texCoord0Offset + 0).ToSingle();
                                texCoord.Y = 1.0f - Half.FromBytes(texCoord0Stream.Data, (j * texCoord0Stream.BytesPerVertex) + texCoord0Offset + 2).ToSingle();
                                break;

                            default:
                                texCoord.X = 0;
                                texCoord.Y = 0;
                                break;
                            }

                            streamWriter.WriteLine("vt " + texCoord.X.ToString(format) + " " + texCoord.Y.ToString(format));
                        }
                    }
                }
            }

            //faces
            UInt32 vertexCount = 0;

            for (Int32 i = 0; i < model.Meshes.Length; ++i)
            {
                Mesh mesh = model.Meshes[i];

                streamWriter.WriteLine("g Mesh" + i);

                for (Int32 j = 0; j < mesh.IndexCount; j += 3)
                {
                    UInt32 index0, index1, index2;

                    switch (mesh.IndexSize)
                    {
                    case 2:
                        index0 = vertexCount + BitConverter.ToUInt16(mesh.IndexData, (j * 2) + 0) + 1;
                        index1 = vertexCount + BitConverter.ToUInt16(mesh.IndexData, (j * 2) + 2) + 1;
                        index2 = vertexCount + BitConverter.ToUInt16(mesh.IndexData, (j * 2) + 4) + 1;
                        break;

                    case 4:
                        index0 = vertexCount + BitConverter.ToUInt32(mesh.IndexData, (j * 4) + 0) + 1;
                        index1 = vertexCount + BitConverter.ToUInt32(mesh.IndexData, (j * 4) + 4) + 1;
                        index2 = vertexCount + BitConverter.ToUInt32(mesh.IndexData, (j * 4) + 8) + 1;
                        break;

                    default:
                        index0 = 0;
                        index1 = 0;
                        index2 = 0;
                        break;
                    }

                    if (exportOptions.Normals && exportOptions.TextureCoordinates)
                    {
                        streamWriter.WriteLine("f " + index2 + "/" + index2 + "/" + index2 + " " + index1 + "/" + index1 + "/" + index1 + " " + index0 + "/" + index0 + "/" + index0);
                    }
                    else if (exportOptions.Normals)
                    {
                        streamWriter.WriteLine("f " + index2 + "//" + index2 + " " + index1 + "//" + index1 + " " + index0 + "//" + index0);
                    }
                    else if (exportOptions.TextureCoordinates)
                    {
                        streamWriter.WriteLine("f " + index2 + "/" + index2 + " " + index1 + "/" + index1 + " " + index0 + "/" + index0);
                    }
                    else
                    {
                        streamWriter.WriteLine("f " + index2 + " " + index1 + " " + index0);
                    }
                }

                vertexCount += (UInt32)mesh.VertexCount;
            }

            streamWriter.Close();
        }
示例#32
0
        /// <summary>
        /// Attemps to export <see cref="Texture"/> specified to the path and mode provided.
        /// </summary>
        /// <param name="key">Key of the Collection Name of the <see cref="Texture"/> to be exported.</param>
        /// <param name="type">Type of the key passed.</param>
        /// <param name="path">Path where the texture should be exported.</param>
        /// <param name="mode">Mode in which export the texture. Range: ".dds", ".png", ".jpg", ".tiff", ".bmp".</param>
        /// <returns>True if texture export was successful, false otherwise.</returns>
        public override bool TryExportTexture(uint key, eKeyType type,
                                              string path, string mode)
        {
            ImageType ddstype;

            switch (mode)
            {
            case ".dds":
                ddstype = ImageType.Dds;
                break;

            case ".png":
                ddstype = ImageType.Png;
                break;

            case ".jpg":
                ddstype = ImageType.Jpg;
                break;

            case ".tiff":
                ddstype = ImageType.Tiff;
                break;

            case ".bmp":
                ddstype = ImageType.Bmp;
                break;

            default:
                return(false);
            }

            var tex = (Texture)this.FindTexture(key, type);

            if (tex == null)
            {
                return(false);
            }

            try
            {
                var data = tex.GetDDSArray();
                if (mode == ".dds")
                {
                    using (var bw = new BinaryWriter(File.Open(path, FileMode.Create)))
                    {
                        bw.Write(data);
                    }
                }
                else
                {
                    using (var sr = new MemoryStream(data))
                        using (var im = new ImageImporter())
                            using (var ex = new ImageExporter())
                            {
                                using (var image = im.LoadImageFromStream(sr))
                                {
                                    ex.SaveImage(image, ddstype, path);
                                }
                            }
                }
                return(true);
            }
            catch (System.Exception) { return(false); }
        }
示例#33
0
        /// <summary>
        /// Attemps to export <see cref="Texture"/> specified to the path and mode provided.
        /// </summary>
        /// <param name="key">Key of the Collection Name of the <see cref="Texture"/> to be exported.</param>
        /// <param name="type">Type of the key passed.</param>
        /// <param name="path">Path where the texture should be exported.</param>
        /// <param name="mode">Mode in which export the texture. Range: ".dds", ".png", ".jpg", ".tiff", ".bmp".</param>
        /// <param name="error">Error occured when trying to clone a texture.</param>
        /// <returns>True if texture export was successful, false otherwise.</returns>
        public override bool TryExportTexture(uint key, eKeyType type,
                                              string path, string mode, out string error)
        {
            error = null;
            ImageType ddstype;

            switch (mode)
            {
            case ".dds":
                ddstype = ImageType.Dds;
                break;

            case ".png":
                ddstype = ImageType.Png;
                break;

            case ".jpg":
                ddstype = ImageType.Jpg;
                break;

            case ".tiff":
                ddstype = ImageType.Tiff;
                break;

            case ".bmp":
                ddstype = ImageType.Bmp;
                break;

            default:
                error = $"{mode} is not a supported image type that can be exported.";
                return(false);
            }

            var tex = (Texture)this.FindTexture(key, type);

            if (tex == null)
            {
                error = $"Texture with key 0x{key:X8} does not exist.";
                return(false);
            }

            try
            {
                var data = tex.GetDDSArray();
                if (mode == ".dds")
                {
                    using (var bw = new BinaryWriter(File.Open(path, FileMode.Create)))
                    {
                        bw.Write(data);
                    }
                }
                else
                {
                    using (var sr = new MemoryStream(data))
                        using (var im = new ImageImporter())
                            using (var ex = new ImageExporter())
                            {
                                using (var image = im.LoadImageFromStream(sr))
                                {
                                    ex.SaveImage(image, ddstype, path);
                                }
                            }
                }
                return(true);
            }
            catch (System.Exception e)
            {
                while (e.InnerException != null)
                {
                    e = e.InnerException;
                }
                error = e.Message;
                return(false);
            }
        }