public static void SavePolygonToImage(Polygon polygon, string fileName, int width, Action <Graphics2D, Affine> render) { var graphicsAndTransform = ImageWithPolygonOutline(polygon, width); render?.Invoke(graphicsAndTransform.graphics, graphicsAndTransform.transform); ImageIO.SaveImageData(fileName, graphicsAndTransform.graphics.DestImage); }
private static void DownloadImageAsync(ImageSequence imageSequenceToLoadInto, string uriToLoad, Action doneLoading, ImageSequence asyncImageSequence, string pngFileName, string gifFileName) { WebClient client = new WebClient(); client.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) => { try // if we get a bad result we can get a target invocation exception. In that case just don't show anything { Task.Run(() => { // scale the loaded image to the size of the target image byte[] raw = e.Result; Stream stream = new MemoryStream(raw); lock (locker) { StaticData.Instance.LoadImageSequenceData(stream, asyncImageSequence); } if (asyncImageSequence.Frames.Count == 1) { // save the as png lock (locker) { if (!File.Exists(pngFileName)) { ImageIO.SaveImageData(pngFileName, asyncImageSequence.Frames[0]); } } } else // save original stream as gif { using (var writter = new FileStream(gifFileName, FileMode.Create)) { stream.Position = 0; stream.CopyTo(writter); } } UiThread.RunOnIdle(() => { imageSequenceToLoadInto.Copy(asyncImageSequence); imageSequenceToLoadInto.Invalidate(); doneLoading?.Invoke(); }); }); } catch { } }; try { client.DownloadDataAsync(new Uri(uriToLoad)); } catch { } }
public static void Paste(this ISceneContext sceneContext) { var scene = sceneContext.Scene; if (Clipboard.Instance.ContainsImage) { // Persist string filePath = ApplicationDataStorage.Instance.GetNewLibraryFilePath(".png"); ImageIO.SaveImageData( filePath, Clipboard.Instance.GetImage()); scene.UndoBuffer.AddAndDo( new InsertCommand( scene, new ImageObject3D() { AssetPath = filePath })); } else if (Clipboard.Instance.ContainsText) { if (Clipboard.Instance.GetText() == "!--IObjectSelection--!") { sceneContext.DuplicateItem(0, ApplicationController.ClipboardItem); // each time we put in the object offset it a bit more pasteObjectXOffset += 5; } } }
public void TakePhoto(string imageFileName) { ImageBuffer noCameraImage = new ImageBuffer(640, 480); Graphics2D graphics = noCameraImage.NewGraphics2D(); graphics.Clear(RGBA_Bytes.White); graphics.DrawString("No Camera Detected", 320, 240, pointSize: 24, justification: Agg.Font.Justification.Center); graphics.DrawString(DateTime.Now.ToString(), 320, 200, pointSize: 12, justification: Agg.Font.Justification.Center); ImageIO.SaveImageData(imageFileName, noCameraImage); PictureTaken?.Invoke(null, null); }
// Download an image from the web into the specified ImageBuffer public static void RetrieveImageAsync(ImageBuffer imageToLoadInto, string uriToLoad, bool scaleToImageX) { var longHash = uriToLoad.GetLongHashCode(); if (scaleToImageX) { longHash = imageToLoadInto.Width.GetLongHashCode(longHash); } var imageFileName = ApplicationController.CacheablePath("Images", longHash.ToString() + ".png"); if (File.Exists(imageFileName)) { try { LoadImageInto(imageToLoadInto, scaleToImageX, null, new StreamReader(imageFileName).BaseStream); return; } catch { } } WebClient client = new WebClient(); client.DownloadDataCompleted += (sender, e) => { try // if we get a bad result we can get a target invocation exception. In that case just don't show anything { Stream stream = new MemoryStream(e.Result); LoadImageInto(imageToLoadInto, scaleToImageX, new BlenderPreMultBGRA(), stream); if (imageToLoadInto.Width > 0 && imageToLoadInto.Height > 0 && !savedImages.Contains(imageFileName)) { savedImages.Add(imageFileName); ImageIO.SaveImageData(imageFileName, imageToLoadInto); } } catch { } }; try { client.DownloadDataAsync(new Uri(uriToLoad)); } catch { } }
public ImageBuffer LoadCachedImage(ILibraryItem libraryItem, int width, int height) { // try to load it from the users cache var expectedCachePath = this.CachePath(libraryItem, width, height); ImageBuffer cachedItem = LoadImage(expectedCachePath); if (cachedItem != null && cachedItem.Width > 0 && cachedItem.Height > 0) { cachedItem.SetRecieveBlender(new BlenderPreMultBGRA()); return(cachedItem); } // if we don't find it see if it in the cache at a bigger size foreach (var cacheSize in cacheSizes.Where(s => s > width)) { cachedItem = LoadImage(this.CachePath(libraryItem, cacheSize, cacheSize)); if (cachedItem != null && cachedItem.Width > 0 && cachedItem.Height > 0) { cachedItem = cachedItem.CreateScaledImage(width, height); cachedItem.SetRecieveBlender(new BlenderPreMultBGRA()); ImageIO.SaveImageData(expectedCachePath, cachedItem); return(cachedItem); } } // could not find it in the user cache, try to load it from static data var staticDataFilename = Path.Combine("Images", "Thumbnails", CacheFilename(libraryItem, 256, 256)); if (StaticData.Instance.FileExists(staticDataFilename)) { cachedItem = StaticData.Instance.LoadImage(staticDataFilename); cachedItem.SetRecieveBlender(new BlenderPreMultBGRA()); cachedItem = cachedItem.CreateScaledImage(width, height); ImageIO.SaveImageData(expectedCachePath, cachedItem); return(cachedItem); } return(null); }
public Task <ImageBuffer> GetThumbnail(ILibraryItem item, int width, int height) { return(Task.Run <ImageBuffer>(async() => { var thumbnail = await LoadImage(item); if (thumbnail != null) { thumbnail = LibraryProviderHelpers.ResizeImage(thumbnail, width, height); // Cache library thumbnail ImageIO.SaveImageData( ApplicationController.Instance.Thumbnails.CachePath(item, width, height), thumbnail); } return thumbnail; })); }
private void CreateOnePage(int plateNumber, ref int nextPartToPrintIndex, PdfPage pdfPage) { ImageBuffer plateInventoryImage = new ImageBuffer((int)(300 * 8.5), 300 * 11); Graphics2D plateGraphics = plateInventoryImage.NewGraphics2D(); double currentlyPrintingHeightPixels = PrintTopOfPage(plateInventoryImage, plateGraphics); Vector2 offset = new Vector2(PageMarginPixels.Left, currentlyPrintingHeightPixels); double tallestHeight = 0; List <PartImage> partsOnLine = new List <PartImage>(); while (nextPartToPrintIndex < partImagesToPrint.Count) { ImageBuffer image = partImagesToPrint[nextPartToPrintIndex].image; tallestHeight = Math.Max(tallestHeight, image.Height); if (partsOnLine.Count > 0 && offset.X + image.Width > plateInventoryImage.Width - PageMarginPixels.Right) { if (partsOnLine.Count == 1) { plateGraphics.Render(partsOnLine[0].image, plateInventoryImage.Width / 2 - partsOnLine[0].image.Width / 2, offset.Y - tallestHeight); } else { foreach (PartImage partToDraw in partsOnLine) { plateGraphics.Render(partToDraw.image, partToDraw.xOffset, offset.Y - tallestHeight); } } offset.X = PageMarginPixels.Left; offset.Y -= (tallestHeight + PartPaddingPixels * 2); tallestHeight = 0; partsOnLine.Clear(); if (offset.Y - image.Height < PageMarginPixels.Bottom) { break; } } else { partImagesToPrint[nextPartToPrintIndex].xOffset = offset.X; partsOnLine.Add(partImagesToPrint[nextPartToPrintIndex]); //plateGraphics.Render(image, offset.x, offset.y - image.Height); offset.X += image.Width + PartPaddingPixels * 2; nextPartToPrintIndex++; } } // print the last line of parts foreach (PartImage partToDraw in partsOnLine) { plateGraphics.Render(partToDraw.image, partToDraw.xOffset, offset.Y - tallestHeight); } TypeFacePrinter printer = new TypeFacePrinter(string.Format("{0}", Path.GetFileNameWithoutExtension(pathAndFileToSaveTo)), 32, justification: Justification.Center); printer.Origin = new Vector2(plateGraphics.DestImage.Width / 2, 110); plateGraphics.Render(printer, Color.Black); printer = new TypeFacePrinter(string.Format("Page {0}", plateNumber), 28, justification: Justification.Center); printer.Origin = new Vector2(plateGraphics.DestImage.Width / 2, 60); plateGraphics.Render(printer, Color.Black); string folderToSavePrintsTo = Path.Combine(ApplicationDataStorage.Instance.ApplicationTempDataPath, "plateImages"); string jpegFileName = Path.Combine(folderToSavePrintsTo, plateNumber.ToString() + ".jpeg"); Directory.CreateDirectory(folderToSavePrintsTo); ImageIO.SaveImageData(jpegFileName, plateInventoryImage); XGraphics gfx = XGraphics.FromPdfPage(pdfPage); XImage jpegImage = XImage.FromFile(jpegFileName); //double width = jpegImage.PixelWidth * 72 / jpegImage.HorizontalResolution; //double height = jpegImage.PixelHeight * 72 / jpegImage. .HorizontalResolution; gfx.DrawImage(jpegImage, 0, 0, pdfPage.Width, pdfPage.Height); }
private static ImageBuffer BuildImageFromMeshGroups(List <MeshGroup> loadedMeshGroups, string stlHashCode, Point2D size) { if (loadedMeshGroups != null && loadedMeshGroups.Count > 0 && loadedMeshGroups[0].Meshes != null && loadedMeshGroups[0].Meshes[0] != null) { ImageBuffer tempImage = new ImageBuffer(size.x, size.y, 32, new BlenderBGRA()); Graphics2D partGraphics2D = tempImage.NewGraphics2D(); partGraphics2D.Clear(new RGBA_Bytes()); AxisAlignedBoundingBox aabb = loadedMeshGroups[0].GetAxisAlignedBoundingBox(); for (int meshGroupIndex = 1; meshGroupIndex < loadedMeshGroups.Count; meshGroupIndex++) { aabb = AxisAlignedBoundingBox.Union(aabb, loadedMeshGroups[meshGroupIndex].GetAxisAlignedBoundingBox()); } double maxSize = Math.Max(aabb.XSize, aabb.YSize); double scale = size.x / (maxSize * 1.2); RectangleDouble bounds2D = new RectangleDouble(aabb.minXYZ.x, aabb.minXYZ.y, aabb.maxXYZ.x, aabb.maxXYZ.y); foreach (MeshGroup meshGroup in loadedMeshGroups) { foreach (Mesh loadedMesh in meshGroup.Meshes) { PolygonMesh.Rendering.OrthographicZProjection.DrawTo(partGraphics2D, loadedMesh, new Vector2((size.x / scale - bounds2D.Width) / 2 - bounds2D.Left, (size.y / scale - bounds2D.Height) / 2 - bounds2D.Bottom), scale, RGBA_Bytes.White); } } if (File.Exists("RunUnitTests.txt")) { foreach (Mesh loadedMesh in loadedMeshGroups[0].Meshes) { List <MeshEdge> nonManifoldEdges = loadedMesh.GetNonManifoldEdges(); if (nonManifoldEdges.Count > 0) { partGraphics2D.Circle(size.x / 4, size.x / 4, size.x / 8, RGBA_Bytes.Red); } } } // and save it to disk string imageFileName = GetFilenameForSize(stlHashCode, size); string folderToSavePrintsTo = Path.GetDirectoryName(imageFileName); if (!Directory.Exists(folderToSavePrintsTo)) { Directory.CreateDirectory(folderToSavePrintsTo); } if (partExtension == ".png") { ImageIO.SaveImageData(imageFileName, tempImage); } else { ImageTgaIO.SaveImageData(imageFileName, tempImage); } // and give it back return(tempImage); } return(null); }
public GuiWidget Create(IObject3D item, UndoBuffer undoBuffer, ThemeConfig theme) { var column = new FlowLayoutWidget(FlowDirection.TopToBottom) { HAnchor = HAnchor.MaxFitOrStretch }; var imageObject = item as ImageObject3D; var activeImage = imageObject.Image; var imageSection = new SearchableSectionWidget("Image".Localize(), new FlowLayoutWidget(FlowDirection.TopToBottom), theme, emptyText: "Search Google".Localize()); imageSection.SearchInvoked += (s, e) => { string imageType = " silhouette"; if (item.Parent.GetType().Name.Contains("Lithophane")) { imageType = ""; } ApplicationController.LaunchBrowser($"http://www.google.com/search?q={e.Data}{imageType}&tbm=isch"); }; theme.ApplyBoxStyle(imageSection, margin: 0); column.AddChild(imageSection); ImageBuffer thumbnailImage = SetImage(theme, imageObject); ImageWidget thumbnailWidget; imageSection.ContentPanel.AddChild(thumbnailWidget = new ImageWidget(thumbnailImage) { Margin = new BorderDouble(bottom: 5), HAnchor = HAnchor.Center }); thumbnailWidget.Click += (s, e) => { if (e.Button == MouseButtons.Right) { var popupMenu = new PopupMenu(theme); var pasteMenu = popupMenu.CreateMenuItem("Paste".Localize()); pasteMenu.Click += (s2, e2) => { activeImage = Clipboard.Instance.GetImage(); thumbnailWidget.Image = activeImage; // Persist string filePath = ApplicationDataStorage.Instance.GetNewLibraryFilePath(".png"); ImageIO.SaveImageData( filePath, activeImage); imageObject.AssetPath = filePath; imageObject.Mesh = null; thumbnailWidget.Image = SetImage(theme, imageObject); column.Invalidate(); imageObject.Invalidate(InvalidateType.Image); }; pasteMenu.Enabled = Clipboard.Instance.ContainsImage; var copyMenu = popupMenu.CreateMenuItem("Copy".Localize()); copyMenu.Click += (s2, e2) => { Clipboard.Instance.SetImage(thumbnailWidget.Image); }; popupMenu.ShowMenu(thumbnailWidget, e); } }; // add in the invert checkbox and change image button var changeButton = new TextButton("Change".Localize(), theme) { BackgroundColor = theme.MinimalShade }; changeButton.Click += (sender, e) => { UiThread.RunOnIdle(() => { // we do this using to make sure that the stream is closed before we try and insert the Picture AggContext.FileDialogs.OpenFileDialog( new OpenFileDialogParams( "Select an image file|*.jpg;*.png;*.bmp;*.gif;*.pdf", multiSelect: false, title: "Add Image".Localize()), (openParams) => { if (!File.Exists(openParams.FileName)) { return; } imageObject.AssetPath = openParams.FileName; using (imageObject.RebuildLock()) { imageObject.Mesh = null; } thumbnailWidget.Image = SetImage(theme, imageObject); column.Invalidate(); imageObject.Invalidate(InvalidateType.Image); }); }); }; var row = new FlowLayoutWidget() { HAnchor = HAnchor.Stretch, VAnchor = VAnchor.Fit, Margin = new BorderDouble(8, 5) }; imageSection.ContentPanel.AddChild(row); // Invert checkbox var invertCheckbox = new CheckBox(new CheckBoxViewText("Invert".Localize(), textColor: theme.TextColor)) { Checked = imageObject.Invert, Margin = new BorderDouble(0), VAnchor = VAnchor.Center, }; invertCheckbox.CheckedStateChanged += (s, e) => { imageObject.Invert = invertCheckbox.Checked; }; row.AddChild(invertCheckbox); row.AddChild(new HorizontalSpacer()); row.AddChild(changeButton); imageObject.Invalidated += (s, e) => { if (e.InvalidateType.HasFlag(InvalidateType.Image) && activeImage != imageObject.Image) { thumbnailImage = SetImage(theme, imageObject); thumbnailWidget.Image = thumbnailImage; activeImage = imageObject.Image; } }; return(column); }
private void CreateThumbnail() { string stlHashCode = this.PrintItem.FileHashCode.ToString(); ImageBuffer bigRender = new ImageBuffer(); if (!File.Exists(this.PrintItem.FileLocation)) { return; } List <MeshGroup> loadedMeshGroups = MeshFileIo.Load(this.PrintItem.FileLocation); RenderType renderType = GetRenderType(this.PrintItem.FileLocation); switch (renderType) { case RenderType.RAY_TRACE: { ThumbnailTracer tracer = new ThumbnailTracer(loadedMeshGroups, BigRenderSize.x, BigRenderSize.y); tracer.DoTrace(); bigRender = tracer.destImage; } break; case RenderType.PERSPECTIVE: { ThumbnailTracer tracer = new ThumbnailTracer(loadedMeshGroups, BigRenderSize.x, BigRenderSize.y); this.thumbnailImage = new ImageBuffer(this.buildingThumbnailImage); this.thumbnailImage.NewGraphics2D().Clear(new RGBA_Bytes(255, 255, 255, 0)); bigRender = new ImageBuffer(BigRenderSize.x, BigRenderSize.y, 32, new BlenderBGRA()); foreach (MeshGroup meshGroup in loadedMeshGroups) { double minZ = double.MaxValue; double maxZ = double.MinValue; foreach (Mesh loadedMesh in meshGroup.Meshes) { tracer.GetMinMaxZ(loadedMesh, ref minZ, ref maxZ); } foreach (Mesh loadedMesh in meshGroup.Meshes) { tracer.DrawTo(bigRender.NewGraphics2D(), loadedMesh, RGBA_Bytes.White, minZ, maxZ); } } if (bigRender == null) { bigRender = new ImageBuffer(this.noThumbnailImage); } } break; case RenderType.NONE: case RenderType.ORTHOGROPHIC: this.thumbnailImage = new ImageBuffer(this.buildingThumbnailImage); this.thumbnailImage.NewGraphics2D().Clear(new RGBA_Bytes(255, 255, 255, 0)); bigRender = BuildImageFromMeshGroups(loadedMeshGroups, stlHashCode, BigRenderSize); if (bigRender == null) { bigRender = new ImageBuffer(this.noThumbnailImage); } break; } // and save it to disk string imageFileName = GetImageFileName(stlHashCode); if (partExtension == ".png") { ImageIO.SaveImageData(imageFileName, bigRender); } else { ImageTgaIO.SaveImageData(imageFileName, bigRender); } ImageBuffer unScaledImage = new ImageBuffer(bigRender.Width, bigRender.Height, 32, new BlenderBGRA()); unScaledImage.NewGraphics2D().Render(bigRender, 0, 0); // If the source image (the one we downloaded) is more than twice as big as our dest image. while (unScaledImage.Width > Width * 2) { // The image sampler we use is a 2x2 filter so we need to scale by a max of 1/2 if we want to get good results. // So we scale as many times as we need to to get the Image to be the right size. // If this were going to be a non-uniform scale we could do the x and y separatly to get better results. ImageBuffer halfImage = new ImageBuffer(unScaledImage.Width / 2, unScaledImage.Height / 2, 32, new BlenderBGRA()); halfImage.NewGraphics2D().Render(unScaledImage, 0, 0, 0, halfImage.Width / (double)unScaledImage.Width, halfImage.Height / (double)unScaledImage.Height); unScaledImage = halfImage; } this.thumbnailImage = new ImageBuffer((int)Width, (int)Height, 32, new BlenderBGRA()); this.thumbnailImage.NewGraphics2D().Clear(new RGBA_Bytes(255, 255, 255, 0)); this.thumbnailImage.NewGraphics2D().Render(unScaledImage, 0, 0, 0, (double)this.thumbnailImage.Width / unScaledImage.Width, (double)this.thumbnailImage.Height / unScaledImage.Height); UiThread.RunOnIdle(this.EnsureImageUpdated); OnDoneRendering(); }
private void CreateThumbnail() { string stlHashCode = this.ItemWrapper.FileHashCode.ToString(); ImageBuffer bigRender = new ImageBuffer(); if (!File.Exists(this.ItemWrapper.FileLocation)) { return; } List <MeshGroup> loadedMeshGroups = MeshFileIo.Load(this.ItemWrapper.FileLocation); RenderType renderType = GetRenderType(this.ItemWrapper.FileLocation); switch (renderType) { case RenderType.RAY_TRACE: { ThumbnailTracer tracer = new ThumbnailTracer(loadedMeshGroups, BigRenderSize.x, BigRenderSize.y); tracer.DoTrace(); bigRender = tracer.destImage; } break; case RenderType.PERSPECTIVE: { ThumbnailTracer tracer = new ThumbnailTracer(loadedMeshGroups, BigRenderSize.x, BigRenderSize.y); this.thumbnailImage = new ImageBuffer(this.buildingThumbnailImage); this.thumbnailImage.NewGraphics2D().Clear(new RGBA_Bytes(255, 255, 255, 0)); bigRender = new ImageBuffer(BigRenderSize.x, BigRenderSize.y); foreach (MeshGroup meshGroup in loadedMeshGroups) { double minZ = double.MaxValue; double maxZ = double.MinValue; foreach (Mesh loadedMesh in meshGroup.Meshes) { tracer.GetMinMaxZ(loadedMesh, ref minZ, ref maxZ); } foreach (Mesh loadedMesh in meshGroup.Meshes) { tracer.DrawTo(bigRender.NewGraphics2D(), loadedMesh, RGBA_Bytes.White, minZ, maxZ); } } if (bigRender == null) { bigRender = new ImageBuffer(this.noThumbnailImage); } } break; case RenderType.NONE: case RenderType.ORTHOGROPHIC: this.thumbnailImage = new ImageBuffer(this.buildingThumbnailImage); this.thumbnailImage.NewGraphics2D().Clear(new RGBA_Bytes(255, 255, 255, 0)); bigRender = BuildImageFromMeshGroups(loadedMeshGroups, stlHashCode, BigRenderSize); if (bigRender == null) { bigRender = new ImageBuffer(this.noThumbnailImage); } break; } // and save it to disk string imageFileName = GetImageFileName(stlHashCode); if (partExtension == ".png") { ImageIO.SaveImageData(imageFileName, bigRender); } else { ImageTgaIO.SaveImageData(imageFileName, bigRender); } bigRender.SetRecieveBlender(new BlenderPreMultBGRA()); this.thumbnailImage = ImageBuffer.CreateScaledImage(bigRender, (int)Width, (int)Height); UiThread.RunOnIdle(this.EnsureImageUpdated); OnDoneRendering(); }
public void RenderToPng(string pngFileName) { ImageIO.SaveImageData(pngFileName, CreateImage(pngFileName)); }
private void ParseJson(string jsonStr) { // parse result FileInfo[] dirContents = JsonConvert.DeserializeObject <FileInfo[]>(jsonStr); var childContainers = new SafeList <ILibraryContainerLink>(); this.Items.Clear(); // read in data foreach (FileInfo file in dirContents) { if (file.type == "dir") { if (file.name == ".images") { ImageUrlCache = new List <(string name, string url)>(); // do the initial load LoadFolderImageUrlCache().Wait(); } else { childContainers.Add(new GitHubContainerLink(file.name, Account, Repository, RepoDirectory + "/" + file.name)); } } else if (file.type == "file") { if (Path.GetExtension(file.name).ToLower() == ".library") { childContainers.Add(new GitHubLibraryLink(Path.GetFileNameWithoutExtension(file.name), Account, Repository, file.download_url)); } else if (file.name == "index.md") { var uri = $"https://raw.githubusercontent.com/{Account}/{Repository}/main/{RepoDirectory}/index.md"; WebCache.RetrieveText(uri, (content) => { HeaderMarkdown = content; OnContentChanged(); }, true, AddCromeHeaders); } else { this.Items.Add(new GitHubLibraryItem(file.name, file.download_url)); } } } Task.Run(async() => { foreach (var item in this.Items) { // check if we have any of the images cached var thumbnail = await Task.Run(() => ApplicationController.Instance.Thumbnails.LoadCachedImage(item, 256, 256)); if (thumbnail != null && thumbnail.Width == 256) { // save so it is easy to create the upload data for GitHub folders var filename = ApplicationController.CacheablePath( Path.Combine("GitHubImages", this.Repository, this.RepoDirectory.Replace("/", "\\"), ".images"), $"{Path.GetFileNameWithoutExtension(item.Name)}.png"); if (!File.Exists(filename)) { ImageIO.SaveImageData(filename, thumbnail); } } } }); this.ChildContainers = childContainers; OnContentChanged(); }