private void Rotate(object sender, RoutedEventArgs e) { if (CurrentPhoto.Source != null) { var img = (BitmapSource)(CurrentPhoto.Source); _undoStack.Push(img); var cache = new CachedBitmap(img, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); CurrentPhoto.Source = new TransformedBitmap(cache, new RotateTransform(90.0)); if (false == UndoButton.IsEnabled) { UndoButton.IsEnabled = true; } if (_cropSelector != null) { #if VISUALCHILD if (Visibility.Visible == CropSelector.Rubberband.Visibility) { CropSelector.Rubberband.Visibility = Visibility.Hidden; } #endif #if NoVISUALCHILD if (CropSelector.ShowRect) { CropSelector.ShowRect = false; } #endif } CropButton.IsEnabled = false; } }
void _show_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { switch (e.PropertyName) { case nameof(FavShowData.Name): Title = _show.Name; break; case nameof(FavShowData.Cover): _dispatcher.Invoke(delegate { Background = new CachedBitmap(_show.Cover); }); break; case nameof(FavShowData.NumberOfEpisodes): case nameof(FavShowData.NumberOfSeasons): RecalcText(); break; case nameof(FavShowData.IsLoading): IsLoadingVisible = (_show.IsLoading) ? Visibility.Visible : Visibility.Collapsed; break; default: if (String.IsNullOrEmpty(e.PropertyName) || e.PropertyName == nameof(FavShowData.Status) || e.PropertyName.StartsWith("NextEpisode") || e.PropertyName.StartsWith("PreviousEpisode") || e.PropertyName == nameof(FavShowData.NewEpisodes) || e.PropertyName == nameof(FavShowData.NewUpdates)) { RecalcNextPrevEpText(); } break; } }
private static BitmapSource ClearArea(BitmapSource frame, FrameMetadata metadata) { DrawingVisual visual = new DrawingVisual(); using (var context = visual.RenderOpen()) { var fullRect = new Rect(0, 0, frame.PixelWidth, frame.PixelHeight); var clearRect = new Rect(metadata.Left, metadata.Top, metadata.Width, metadata.Height); var clip = Geometry.Combine( new RectangleGeometry(fullRect), new RectangleGeometry(clearRect), GeometryCombineMode.Exclude, null); context.PushClip(clip); context.DrawImage(frame, fullRect); } var bitmap = new RenderTargetBitmap( frame.PixelWidth, frame.PixelHeight, frame.DpiX, frame.DpiY, PixelFormats.Pbgra32); bitmap.Render(visual); var result = new CachedBitmap(bitmap, BitmapCreateOptions.None, BitmapCacheOption.Default); if (result.CanFreeze && !result.IsFrozen) { result.Freeze(); } return(result); }
/// <summary> /// 画像のStreamから埋め込みサムネイル優先でBitmapSourceを作成する /// </summary> /// <param name="stream"></param> /// <param name="widthMax">埋め込みサムネイルが存在しなかった場合に、主画像をリサイズする最大幅</param> /// <returns></returns> private static BitmapSource ToBitmapSourceFromEmbeddedThumbnail(this Stream stream, double widthMax) { if (stream is null) { throw new ArgumentNullException(nameof(stream)); } var image = BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.None); BitmapSource bitmap; if (image.Thumbnail != null) { bitmap = image.Thumbnail; } else { var longSide = Math.Max(image.PixelWidth, image.PixelHeight); if (longSide == 0) { throw new DivideByZeroException(nameof(longSide)); } var scale = widthMax / (double)longSide; var thumbnail = new TransformedBitmap(image, new ScaleTransform(scale, scale)); var cache = new CachedBitmap(thumbnail, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); cache.Freeze(); bitmap = (BitmapSource)cache; // アップキャストは常に合法 } return(bitmap); }
void _show_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (e.PropertyName == "Name") { Title = _show.Name; } else if (e.PropertyName == "Cover") { _dispatcher.Invoke(delegate { Background = new CachedBitmap(_show.Cover); }); } else if (e.PropertyName == "NumberOfEpisodes" || e.PropertyName == "NumberOfSeasons") { RecalcText(); } else if (e.PropertyName == "NewEpisodes") { NewEpisodesVisible = (_show.NewEpisodes) ? Visibility.Visible : Visibility.Collapsed; } else if (e.PropertyName == "IsLoading") { IsLoadingVisible = (_show.IsLoading) ? Visibility.Visible : Visibility.Collapsed; } }
//------------- Конец: Фильтры обнаружения края -------------- //-------------------- Начало: Поворот --------------------- public static void Rotate(Layer photo, double angle) { BitmapSource img = photo.LayerBmpFrame; CachedBitmap cache = new CachedBitmap(img, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); photo.LayerBmpFrame = BitmapFrame.Create(new TransformedBitmap(cache, new RotateTransform(angle))); }
/// <summary> /// 引数PATHをサムネイルとして読み出す /// </summary> /// <param name="imagePath">ファイルパス</param> /// <param name="width">サムネイルの画像幅</param> /// <returns></returns> public static BitmapSource LoadThumbnail(this string imagePath, int width = DefaultThumbnailWidth) { if (imagePath is null) { throw new ArgumentNullException(nameof(imagePath)); } if (!File.Exists(imagePath)) { throw new FileNotFoundException(imagePath); } using (var stream = File.Open(imagePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BitmapSource bitmapSource = null; var img = BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.None); if (img.Thumbnail != null) { bitmapSource = img.Thumbnail; // サムネイル読み出し高速化 } else { bitmapSource = img as BitmapSource; } var longSide = Math.Max(bitmapSource.PixelWidth, bitmapSource.PixelHeight); var scale = width / (double)longSide; var thumbnail = new TransformedBitmap(bitmapSource, new ScaleTransform(scale, scale)); var cachedBitmap = new CachedBitmap(thumbnail, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); cachedBitmap.Freeze(); return((BitmapSource)cachedBitmap); // アップキャストは常に合法 } }
private void SerializeGeneratedWorkaround(Material material, string masterFileName, List <string> supportFiles) { // This is method is needed because of this issue: // ( if (material is MaterialGroup) { foreach (Material m in ((MaterialGroup)material).Children) { SerializeGeneratedWorkaround(m, masterFileName, supportFiles); } } else { Brush brush = null; if (material is DiffuseMaterial) { DiffuseMaterial dm = (DiffuseMaterial)material; brush = dm.Brush; } else if (material is EmissiveMaterial) { EmissiveMaterial em = (EmissiveMaterial)material; brush = em.Brush; } else if (material is SpecularMaterial) { SpecularMaterial sm = (SpecularMaterial)material; brush = sm.Brush; } if (brush is ImageBrush) { ImageBrush ib = (ImageBrush)brush; // NOTE: Other forms of memory-generated bitmaps may need the same treatment. if (ib.ImageSource is CachedBitmap) { CachedBitmap cb = (CachedBitmap)ib.ImageSource; // Generate new file Name int fileIndex = supportFiles.Count; string fileName = masterFileName.Replace(".xaml", "_support_") + fileIndex.ToString() + ".png"; // Save as an image file (PNG to keep transparency) PhotoConverter.SaveImageAs(cb, fileName); // Remember the name supportFiles.Add(fileName); // Now replace this in the old brush ib.ImageSource = new BitmapImage(new Uri(fileName, UriKind.RelativeOrAbsolute)); ib.ViewboxUnits = BrushMappingMode.RelativeToBoundingBox; } } // The default case is for this to be a NO-OP } }
private void Rotate(object sender, RoutedEventArgs e) { BitmapSource img = (BitmapSource)(_photo.Image); CachedBitmap cache = new CachedBitmap(img, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); _photo.Image = BitmapFrame.Create(new TransformedBitmap(cache, new RotateTransform(90.0))); ViewedPhoto.Source = _photo.Image; }
public static CachedBitmap extractRegion(this CachedBitmap source, int x, int y, int w, int h) { Image canvas = new Bitmap(w, h, PixelFormat.Format24bppRgb); Rectangle rect = new Rectangle(x, y, w, h); Bitmap partSrc = source.Bitmap.Clone(rect, PixelFormat.Format24bppRgb); using (Graphics g = Graphics.FromImage(canvas)) { g.DrawImage(partSrc, 0, 0, w, h); } return(new CachedBitmap((Bitmap)canvas.Clone())); }
public static Bitmap ResizeToBitmap(this CachedBitmap img, int width, int height) { if (img.Width == width && img.Height == height) { return(img.Bitmap); } Bitmap b = new Bitmap(width, height); using (Graphics g = Graphics.FromImage(b)) { g.DrawImage(img.Bitmap, 0, 0, width, height); } return(b); }
void OnLoaded(object sender, EventArgs e) { #if !DEBUG Topmost = true; MouseMove += new MouseEventHandler(PhotoStack_MouseMove); MouseDown += new MouseButtonEventHandler(PhotoStack_MouseDown); KeyDown += new KeyEventHandler(PhotoStack_KeyDown); #endif DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer(); //find all valid images var files = (from file in new DirectoryInfo(Settings.PictureFolder).GetFiles() where Settings.ValidExtensions.Any(ext => ext.Equals(file.Extension)) select file).ToArray(); pictures = new CachedBitmap[files.Count()]; for (int i = 0; i < pictures.Count(); i++) { pictures[i] = new CachedBitmap(new BitmapImage(new Uri(files[i].FullName)), BitmapCreateOptions.None, BitmapCacheOption.OnLoad); } //todo: shuffle array if (pictures.Length > 0) { ////load first image firstImage.Source = pictures[random.Next(pictures.Count())]; //fade in Storyboard fadeIn = (Storyboard)FindResource("fadeIn"); Dispatcher.BeginInvoke(new Action(fadeIn.Begin), DispatcherPriority.Normal); ////start timer to switch pictures dispatcherTimer.Tick += new EventHandler(ChangePhotos); } if (Settings.ShowClock) { //update clock UpdateTime(null, null); dispatcherTimer.Tick += new EventHandler(UpdateTime); } else { clockPanel.Visibility = Visibility.Collapsed; } dispatcherTimer.Interval = Settings.ChangeInterval; dispatcherTimer.Start(); }
public System.Windows.Media.Imaging.BitmapSource GetThumbnail(int width, int height) { BitmapSource thumb = null; // Try to read the thumbnail. if (Frame.Thumbnail != null) { try { double scale; scale = (Math.Min(width / (double)Frame.Thumbnail.PixelWidth, height / (double)Frame.Thumbnail.PixelHeight)); thumb = Scale(Frame.Thumbnail, scale); } catch { if (thumb != null) { thumb = null; } } } // Try to read the preview. if (thumb == null && Frame.Decoder?.Preview != null) { try { double scale; var preview = Frame.Decoder.Preview; scale = (Math.Min(width / (double)preview.PixelWidth, height / (double)preview.PixelHeight)); thumb = Scale(preview, scale); } catch { if (thumb != null) { thumb = null; } } } if (thumb == null) { double scale; scale = (Math.Min(width / (double)Frame.PixelWidth, height / (double)Frame.PixelHeight)); thumb = Scale(Frame, scale); } var retval = new CachedBitmap(thumb, BitmapCreateOptions.None, BitmapCacheOption.Default); retval.Freeze(); return(retval); }
public static void SetPixel(this CachedBitmap img, int x, int y, byte r, byte g, byte b) { if (x < 0 || y < 0 || x >= img.Width || y >= img.Height) { return; } int index = (y * img.Width + x); if (index * 3 > img.Binary.Length) { return; } img.Binary[index * 3 + 54] = b; img.Binary[index * 3 + 55] = g; img.Binary[index * 3 + 56] = r; }
/// <summary> /// 引数PATHをサムネイルとして読み出す /// </summary> /// <param name="imagePath">ファイルパス</param> /// <param name="widthMax">サムネイルの画像幅</param> /// <returns></returns> public static BitmapSource?ToBitmapSourceThumbnail(this string imagePath, double widthMax) { if (!File.Exists(imagePath)) { return(null); //throw new FileNotFoundException(imagePath); } using var stream = File.Open(imagePath, FileMode.Open, FileAccess.Read, FileShare.Read); var img = BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.None); var bitmapSource = img.Thumbnail ?? (img as BitmapSource); var longSide = Math.Max(bitmapSource.PixelWidth, bitmapSource.PixelHeight); var scale = widthMax / (double)longSide; var thumbnail = new TransformedBitmap(bitmapSource, new ScaleTransform(scale, scale)); var cachedBitmap = new CachedBitmap(thumbnail, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); cachedBitmap.Freeze(); return((BitmapSource)cachedBitmap); // アップキャストは常に合法 }
public ShowTileViewModel(FavShowData show) { _dispatcher = Dispatcher.CurrentDispatcher; _show = show; // _showViewModel = new ShowViewModel(_show); Title = _show.Name; IsLoadingVisible = (_show.IsLoading) ? Visibility.Visible : Visibility.Collapsed; RecalcText(); if (!String.IsNullOrWhiteSpace(_show.Cover)) { Background = new CachedBitmap(_show.Cover); } else { Background = null; } _show.PropertyChanged += _show_PropertyChanged; }
/// <Summary> /// Gets a software copy of D3DImage. Called by printing, RTB, and BMEs. The /// user can override this to return something else in the case of the /// device lost, for example. /// </Summary> protected internal virtual BitmapSource CopyBackBuffer() { BitmapSource copy = null; if (_pInteropDeviceBitmap != null) { BitmapSourceSafeMILHandle pIWICBitmapSource; if (HRESULT.Succeeded(UnsafeNativeMethods.InteropDeviceBitmap.GetAsSoftwareBitmap( _pInteropDeviceBitmap, out pIWICBitmapSource ))) { // CachedBitmap will AddRef the bitmap copy = new CachedBitmap(pIWICBitmapSource); } } return(copy); }
private static BitmapSource MakeFrame( Int32Size fullSize, BitmapSource rawFrame, FrameMetadata metadata, BitmapSource baseFrame) { if (baseFrame == null && IsFullFrame(metadata, fullSize)) { // No previous image to combine with, and same size as the full image // Just return the frame as is return(rawFrame); } DrawingVisual visual = new DrawingVisual(); using (var context = visual.RenderOpen()) { if (baseFrame != null) { var fullRect = new Rect(0, 0, fullSize.Width, fullSize.Height); context.DrawImage(baseFrame, fullRect); } var rect = new Rect(metadata.Left, metadata.Top, metadata.Width, metadata.Height); context.DrawImage(rawFrame, rect); } var bitmap = new RenderTargetBitmap( fullSize.Width, fullSize.Height, 96, 96, PixelFormats.Pbgra32); bitmap.Render(visual); var result = new CachedBitmap(bitmap, BitmapCreateOptions.None, BitmapCacheOption.Default); if (result.CanFreeze && !result.IsFrozen) { result.Freeze(); } return(result); }
private static BitmapFrame RotateImage(BitmapFrame frame, double angle) { TiffBitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Frames.Add(frame); MemoryStream stream = new MemoryStream(); encoder.Save(stream); BitmapImage imageSource = new BitmapImage(); imageSource.BeginInit(); imageSource.StreamSource = stream; imageSource.EndInit(); CachedBitmap cache = new CachedBitmap(imageSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); TransformedBitmap tb = new TransformedBitmap(cache, new RotateTransform(angle)); return(BitmapFrame.Create(tb)); }
private RibbonModelGalleryCategory CreateFruitGalleryCategory() { void AddFruidDrawing(string assetDrawing1, RibbonModelGalleryCategory modelGalleryCategory1) { var ii = TryFindResource(assetDrawing1) as DrawingGroup; DrawingBrush db = new DrawingBrush(ii); // Matrix transformToDevice; // using (var source = new HwndSource(new HwndSourceParameters())) // transformToDevice = source.CompositionTarget.TransformToDevice; // var pixelSize = (Size)transformToDevice.Transform((Vector)ii.Bounds.Size); double width, height; if (ii.Bounds.Width > ii.Bounds.Height) { width = 32.0; height = ii.Bounds.Height / ii.Bounds.Width * 32.0; } else { height = 32.0; width = ii.Bounds.Width / ii.Bounds.Height * 32.0; } Rectangle r = new Rectangle() { Fill = db, Width = width, Height = height }; modelGalleryCategory1.Items.Add(r); } var modelGalleryCategory = new RibbonModelGalleryCategory { Header = "Fruits" }; void AddFruit(string s, RibbonModelGalleryCategory galleryCategory) { void AddFruitImage(object content, string s1) { var fruit1 = new RibbonModelGalleryItem() { Content = content }; galleryCategory.Items.Add(fruit1); } var grapes1 = new Rectangle(); grapes1.Width = 32; grapes1.Height = 32; var tryFindResource = (BitmapSource)TryFindResource(s); ImageBrush i = new ImageBrush(tryFindResource); i.Freeze(); CachedBitmap x = new CachedBitmap((BitmapSource)TryFindResource(s), BitmapCreateOptions.None, BitmapCacheOption.Default); BitmapCacheBrush xx = new BitmapCacheBrush(); BitmapCache xxx = new BitmapCache(); grapes1.CacheMode = xxx; grapes1.Fill = new ImageBrush(x); grapes1.Tag = s; AddFruitImage(new Border { Background = i, Width = tryFindResource.PixelWidth, Height = tryFindResource.PixelHeight }, s); } var grapes = "Grapes"; var assetDrawing = "Asset_3Drawing"; AddFruidDrawing(assetDrawing, modelGalleryCategory); AddFruidDrawing("Asset_4Drawing", modelGalleryCategory); AddFruidDrawing("Asset_2Drawing", modelGalleryCategory); // AddFruidDrawing("Asset_4Drawing", modelGalleryCategory); // AddFruidDrawing("Asset_4Drawing", modelGalleryCategory); // AddFruit(grapes, modelGalleryCategory); // AddFruit("Watermelon", modelGalleryCategory); // AddFruit("Strawberry", modelGalleryCategory); // modelGalleryCategory.Items.Add(new Rectangle { Stroke = Brushes.Green, StrokeThickness = 3.0, Width = 32, Height = 32}); return(modelGalleryCategory); }
private void Close_Click(object sender, RoutedEventArgs e) { // MessageBox.Show(sender.ToString() + " "+e.ToString()); if (this.EditPnl.SaveState && this.imageOn.Source != null /* && this.EditPnl.Angle != 0*/) { BitmapEncoder encoder; string tmp = FileName; string imageFormat = tmp.Substring(tmp.LastIndexOf('.') + 1); MessageBox.Show(imageFormat); for (int i = 1; ; i++) { if (!File.Exists(FileName)) { break; } try { FileName = FileName.Remove(this.FileName.LastIndexOf('(')); } catch (ArgumentOutOfRangeException) { FileName = FileName.Remove(this.FileName.LastIndexOf('.')); } FileName += '(' + i.ToString() + ")." + imageFormat; } switch (imageFormat) { case "jpeg": encoder = new JpegBitmapEncoder(); break; case "png": encoder = new PngBitmapEncoder(); break; case "bmp": encoder = new BmpBitmapEncoder(); break; case "tiff": encoder = new TiffBitmapEncoder(); break; case "wmp": encoder = new WmpBitmapEncoder(); break; case "gif": encoder = new GifBitmapEncoder(); break; default: encoder = new PngBitmapEncoder(); break; } CachedBitmap cache = new CachedBitmap((BitmapSource)this.imageOn.Source, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); TransformedBitmap tb = new TransformedBitmap(cache, new RotateTransform(EditPnl.Angle)); encoder.Frames.Add(BitmapFrame.Create(tb)); using (FileStream file = File.Create(this.FileName)) { encoder.Save(file); } } this.Close(); }
private void CreateAndShowMainWindow() { // Create the application's main window mainWindow = new Window(); mainWindow.Title = "CachedBitmap Imaging Sample"; // Create a BitmapSource using a Uri BitmapSource source = BitmapFrame.Create(new Uri("tulipfarm.jpg", UriKind.RelativeOrAbsolute)); // Create a new BitmapSource by scaling the original one. //<Snippet1> TransformedBitmap scaledSource = new TransformedBitmap(); scaledSource.BeginInit(); scaledSource.Source = source; scaledSource.Transform = new ScaleTransform(5, 5, 25, 25); scaledSource.EndInit(); //</Snippet1> // Create a cache for the scaled BitmapSource // OnLoad will create the cache as soon as the new BitmapSource is created. //<Snippet4> //<Snippet2> CachedBitmap cachedSource = new CachedBitmap( scaledSource, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); //</Snippet2> //<Snippet3> // Create a new BitmapSource using a different format than the original one. FormatConvertedBitmap newFormatSource = new FormatConvertedBitmap(); newFormatSource.BeginInit(); newFormatSource.Source = cachedSource; newFormatSource.DestinationFormat = PixelFormats.Gray32Float; newFormatSource.EndInit(); //</Snippet3> //</Snippet4> // Define an Image Control to host the FormatConvertedImage Image myImage = new Image(); myImage.Source = newFormatSource; // Define a StackPanel to host Content StackPanel myStackPanel = new StackPanel(); myStackPanel.Orientation = Orientation.Vertical; myStackPanel.VerticalAlignment = VerticalAlignment.Stretch; myStackPanel.HorizontalAlignment = HorizontalAlignment.Stretch; // Add the Image and TextBlock to the parent Grid myStackPanel.Children.Add(myImage); // Add the StackPanel as the Content of the Parent Window Object mainWindow.Content = myStackPanel; mainWindow.Show(); }