public BitmapSource Convert(Bitmap bitmap) { var bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat); var bitmapSource = BitmapSource.Create(bitmapData.Width, bitmapData.Height, 96, 96, PixelFormats.Bgr32, null, bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride); bitmap.UnlockBits(bitmapData); bitmapSource.Freeze(); // make it readable on any thread // crop border var cropLeft = Math.Max(0, CropLeft); var cropTop = Math.Max(0, CropTop); var cropRight = Math.Max(0, CropRight); var cropBottom = Math.Max(0, CropBottom); if (bitmapSource.PixelWidth - cropLeft - cropRight <= 0) { throw new CropRectangleOutOfRangeException("With a width of " + bitmapSource.PixelWidth + ", left crop of " + cropLeft + " and right crop of " + cropRight + ", there is no surface left to grab."); } if (bitmapSource.PixelHeight - cropTop - cropBottom <= 0) { throw new CropRectangleOutOfRangeException("With a height of " + bitmapSource.PixelHeight + ", top crop of " + cropTop + " and bottom crop of " + cropBottom + ", there is no surface left to grab."); } var rect = new Int32Rect(cropLeft, cropTop, bitmapSource.PixelWidth - cropLeft - cropRight, bitmapSource.PixelHeight - cropTop - cropBottom); var img = new CroppedBitmap(bitmapSource, rect); img.Freeze(); return(img); }
/// <summary> /// Correctly creates a cropped bitmap /// </summary> private void CreateCroppedBitmap() { if (MainWindow.IsArmorLike(ItemType)) { CroppedBitmap = new CroppedBitmap(SourceImage, ImageHandler.GetCropRect(Frames, CurrentFrame, SourceImage)); } else { CroppedBitmap = new CroppedBitmap(SourceImage, new Int32Rect(0, 0, SourceImage.PixelWidth, SourceImage.PixelHeight)); } try { ImageElement.Source = null; ImageElement.Source = CroppedBitmap; } catch (InvalidOperationException e) { CroppedBitmap tempBitmap = CroppedBitmap.Clone(); tempBitmap.Freeze(); App.Current.Dispatcher.Invoke(() => { ImageElement.Source = tempBitmap; }); CroppedBitmap = tempBitmap; Console.WriteLine(e); } }
private static BitmapEncoder CopyRegionIntoImage(BitmapImage srcBitmap, Rect srcRegion, Rect destRegion, Func <BitmapEncoder> encoderMaker) { CroppedBitmap cropped = new CroppedBitmap(srcBitmap, ToInt32Rect(srcRegion)); cropped.Freeze(); var scale = 256.0 / srcRegion.Width; var transform = new ScaleTransform(scale, scale); DrawingVisual drawingVisual = new DrawingVisual(); using (DrawingContext drawingContext = drawingVisual.RenderOpen()) { drawingContext.DrawImage(new TransformedBitmap(cropped, transform), destRegion); } RenderTargetBitmap bmp = new RenderTargetBitmap(256, 256, 96, 96, PixelFormats.Pbgra32); bmp.Render(drawingVisual); bmp.Freeze(); var encoder = encoderMaker(); encoder.Frames.Add(BitmapFrame.Create(bmp)); return(encoder); }
private static WriteableBitmap CropFrame(ref Rectangle srcRect, BitmapSource source) { var x = Math.Min(srcRect.X, source.PixelWidth - 1); var y = Math.Min(srcRect.Y, source.PixelHeight - 1); x = Math.Max(x, 0); y = Math.Max(y, 0); var right = srcRect.X + srcRect.Width; right = Math.Min(right, source.PixelWidth); right = Math.Max(right, 0); var bottom = srcRect.Y + srcRect.Height; bottom = Math.Min(bottom, source.PixelHeight); bottom = Math.Max(bottom, 0); var crop = new CroppedBitmap(source, new Int32Rect(x, y, right - x, bottom - y)); crop.Freeze(); var bmp = BitmapFactory.ConvertToPbgra32Format(crop); return(bmp); }
public BitmapSource GetTile(SymbolID symbolID, GameColor color, int tileSize) { var key = new TileKey(symbolID, color, tileSize); BitmapSource bmp; if (m_cache.TryGet(key, out bmp)) { return(bmp); } int xOffset = GetTileXOffset(tileSize); int yOffset = GetTileYOffset(symbolID); bmp = new CroppedBitmap(this.Atlas, new Int32Rect(xOffset, yOffset, tileSize, tileSize)); if (color != GameColor.None) { var rgb = color.ToGameColorRGB(); var wcolor = Color.FromRgb(rgb.R, rgb.G, rgb.B); bmp = ColorizeBitmap(bmp, wcolor); } bmp.Freeze(); m_cache.Add(key, bmp); return(bmp); }
protected override void DecodeData() { Dictionary <String, BitmapSource> ImagesBoard = ReadImages(); IdToKey.Clear(); KeyToName.Clear(); foreach (ChampionDto champion in ChampionList.data.Values) { try { ImageDto image = champion.image; IdToKey.Add(champion.id, champion.key); KeyToName.Add(champion.key, champion.name); string imagePath = DirectoryPath + champion.image.sprite; if (!ImagesBoard.ContainsKey(imagePath)) { String url = String.Format("http://ddragon.leagueoflegends.com/cdn/{0}/img/sprite/{1}", ChampionList.version, champion.image.sprite); File.Delete(imagePath); Utilities.DownloadFile(url, imagePath); ImagesBoard.Add(imagePath, Utilities.GetBitmapImage(imagePath)); } ImageSource cropped = new CroppedBitmap(ImagesBoard[imagePath], new Int32Rect(image.x + 3, image.y + 3, image.w - 6, image.h - 6)); cropped.Freeze(); //一定要Freeze,因為跨Thread if (Images.ContainsKey(champion.key)) { Images.Remove(champion.key); } Images.Add(champion.key, cropped); } catch (Exception) { } } }
protected override void DecodeData() { Dictionary <String, BitmapSource> ImagesBoard = ReadImages(); foreach (ItemDto item in ItemList.data.Values) { try { ImageDto image = item.image; string imagePath = DirectoryPath + item.image.sprite; if (!ImagesBoard.ContainsKey(imagePath)) { String url = String.Format("http://ddragon.leagueoflegends.com/cdn/{0}/img/sprite/{1}", ItemList.version, item.image.sprite); File.Delete(imagePath); Utilities.DownloadFile(url, imagePath); ImagesBoard.Add(imagePath, Utilities.GetBitmapImage(imagePath)); } ImageSource cropped = new CroppedBitmap(ImagesBoard[imagePath], new Int32Rect(image.x, image.y, image.w, image.h)); cropped.Freeze(); //一定要Freeze,因為跨Thread if (Images.ContainsKey(item.id)) { Images.Remove(item.id); } Images.Add(item.id, cropped); } catch (Exception) { } } }
private static ImageSource GetImageSource() { BitmapSource source = ImageHelper.BitmapSourceFromBitmap(new Bitmap(Image.FromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream("Paket.VisualStudio.Resources.NuGet.ico")))); Int32Rect sourceRect = new Int32Rect(0, 0, 16, 16); ImageSource imageSource = new CroppedBitmap(source, sourceRect); imageSource.Freeze(); return imageSource; }
private void prepareForUpload(UploadArgs args) { // freeze the image so the background thread can access it image.Freeze(); // show progress bar actionProgress.Visibility = System.Windows.Visibility.Visible; worker.RunWorkerAsync(args); }
public Task <BitmapSource> TakePartialScreenshot(Int32Rect rpRect) { return(TakeScreenshot(r => { var rResult = new CroppedBitmap(r, rpRect); rResult.Freeze(); return rResult; })); }
public static BitmapSource GetPackedBitmap(string uriString, int x, int y, int width, int height) { var bitmapImage = new BitmapImage(new Uri(uriString, UriKind.RelativeOrAbsolute)); bitmapImage.Freeze(); var croppedBitmap = new CroppedBitmap(bitmapImage, new Int32Rect(x, y, width, height)); croppedBitmap.Freeze(); return(croppedBitmap); }
protected override bool RealizeImage(int index, out BitmapSource image) { if ((index < 0) || (index >= this.BaseImageCount)) { image = null; return(false); } int x = index * base.IconWidth; Int32Rect sourceRect = new Int32Rect(x, 0, base.IconWidth, base.IconHeight); image = new CroppedBitmap(this._imageStrip, sourceRect); image.Freeze(); return(true); }
public BitmapSource GetSelectBitmap() { var x = (int)SelectX; var y = (int)SelectY; var width = (int)SelectWidth + 1; var height = (int)SelectHeight + 1; var bitmap = BackgroundBitmap; var result = new CroppedBitmap(bitmap, new Int32Rect(x, y, width, height)); if (result.CanFreeze) { result.Freeze(); } return(result); }
private void SetCroppedImg(BitmapSource fullImg, Image imgOnScreen, ImgOrientation o) { imgOnScreen.Source = null; double ratio = (double)mSlider.Value / (double)mSlider.Maximum; double gridWidth = mGridMain.ColumnDefinitions[1].ActualWidth; double imgRenderHeight = fullImg.PixelHeight * (gridWidth / fullImg.PixelWidth); imgOnScreen.Height = imgRenderHeight; var cropRect = new Int32Rect(); switch (o) { case ImgOrientation.Left: cropRect = new Int32Rect(0, 0, (int)(fullImg.PixelWidth * ratio), fullImg.PixelHeight); if (cropRect.Width == 0) { cropRect.Width = 1; } if (fullImg.PixelWidth < cropRect.Width) { cropRect.Width = fullImg.PixelWidth; } imgOnScreen.Width = gridWidth * ratio; break; case ImgOrientation.Right: cropRect = new Int32Rect((int)(fullImg.PixelWidth * ratio), 0, (int)(fullImg.PixelWidth * (1.0 - ratio)), fullImg.PixelHeight); if (cropRect.Width == 0) { cropRect.Width = 1; cropRect.X = fullImg.PixelWidth - 1; } imgOnScreen.Width = gridWidth * (1.0 - ratio); break; } var cropImg = new CroppedBitmap(fullImg, cropRect); cropImg.Freeze(); imgOnScreen.Source = cropImg; }
/// <summary> /// When implemented in a derived class, returns an object that is provided as the value of /// the target property for this markup extension. /// </summary> /// <param name="serviceProvider"> /// A service provider helper that can provide services for the markup extension. /// </param> /// <returns> /// The object value to set on the property where the extension is applied. /// </returns> public override object ProvideValue(IServiceProvider serviceProvider) { // Setting BitmapImage.SourceRect has no effect. Need to use CroppedBitmap. if (WindowsHelper.IsInDesignMode) { // ----- Design time: // Design mode requires special code when used inside a WPF styles. var bitmapImage = Source as BitmapImage; if (bitmapImage == null) { return(null); } var croppedBitmap = new CroppedBitmap(); croppedBitmap.BeginInit(); croppedBitmap.Source = new BitmapImage(bitmapImage.UriSource); croppedBitmap.SourceRect = SourceRect; croppedBitmap.EndInit(); croppedBitmap.Freeze(); return(croppedBitmap); } else { // ----- Run time: var bitmapSource = Source as BitmapSource; if (bitmapSource == null) { return(null); } // Freeze bitmap for performance. bitmapSource.Freeze(); var croppedBitmap = new CroppedBitmap(bitmapSource, SourceRect); croppedBitmap.Freeze(); return(croppedBitmap); } }
public BitmapSource TakePartialScreenshot(Int32Rect rpRect) { return(TakeScreenshot(r => { var rBrowserWindowHandle = ServiceManager.GetService <IBrowserService>().Handle; NativeStructs.RECT rBrowserWindowRect; NativeMethods.User32.GetWindowRect(rBrowserWindowHandle, out rBrowserWindowRect); var rHorizontalRatio = rBrowserWindowRect.Width / GameConstants.GameWidth; var rVerticalRatio = rBrowserWindowRect.Height / GameConstants.GameHeight; rpRect.X = (int)(rpRect.X * rHorizontalRatio); rpRect.Y = (int)(rpRect.Y * rVerticalRatio); rpRect.Width = (int)(rpRect.Width * rHorizontalRatio); rpRect.Height = (int)(rpRect.Height * rVerticalRatio); var rResult = new CroppedBitmap(r, rpRect); rResult.Freeze(); return rResult; })); }
public CroppedBitmap BitmapForChar(char c) { if (_fontBitmapImage == null) { Logging.Warning("_fontBitmapImage == null!"); return(null); } if (_fontList == null) { Logging.Warning("_fontList == null!"); return(null); } var i = CharToId(c); var x = _fontList[i]; var width = (i + 1 == _fontList.Count ? 1d : _fontList[i + 1]) - x; if (x + width <= 0d || x >= 1d) { return(null); } if (x < 0) { width += x; x = 0d; } width = Math.Min(width, 1d - x); var rect = new Int32Rect((int)(x * _fontBitmapImage.PixelWidth), 0, (int)(width * _fontBitmapImage.PixelWidth), _fontBitmapImage.PixelHeight); var result = new CroppedBitmap(_fontBitmapImage, rect); result.Freeze(); return(result); }
public override BitmapSource Process(BitmapSource bmp) { var sw = new Stopwatch(); sw.Start(); var sliceWidth = bmp.Width / (Width + Width * Spacing - Spacing); var sliceHeight = bmp.Height / (Height + Height * Spacing - Spacing); var paddingWidth = (bmp.Width * Spacing) / (Width + Width * Spacing - Spacing); var paddingHeight = (bmp.Height * Spacing) / (Height + Height * Spacing - Spacing); var destRect = new Int32Rect(); var srcRect = new Int32Rect(); var bytesPerPixel = (bmp.Format.BitsPerPixel + 7) / 8; var wBmp = new WriteableBitmap(bmp); srcRect.Y = 0; srcRect.Width = (int)Math.Ceiling(sliceWidth); srcRect.Height = bmp.PixelHeight; destRect.Y = 0; destRect.Width = srcRect.Width; destRect.Height = bmp.PixelHeight; var blockSize = bytesPerPixel * srcRect.Width * bmp.PixelHeight; var stride = srcRect.Width * bytesPerPixel; var buffer = new byte[blockSize]; for (var x = 0; x < Width; x++) { srcRect.X = (int)(x * (sliceWidth + paddingWidth)); destRect.X = (int)(x * sliceWidth); bmp.CopyPixels(srcRect, buffer, stride, 0); wBmp.WritePixels(destRect, buffer, stride, 0); } srcRect.X = 0; srcRect.Width = bmp.PixelWidth; srcRect.Height = (int)Math.Ceiling(sliceHeight); destRect.X = 0; destRect.Width = bmp.PixelWidth; destRect.Height = srcRect.Height; blockSize = bytesPerPixel * bmp.PixelWidth * srcRect.Height; stride = bmp.PixelWidth * bytesPerPixel; buffer = new byte[blockSize]; for (var y = 0; y < Height; y++) { srcRect.Y = (int)(y * (sliceHeight + paddingHeight)); destRect.Y = (int)(y * sliceHeight); wBmp.CopyPixels(srcRect, buffer, stride, 0); wBmp.WritePixels(destRect, buffer, stride, 0); } var img = new CroppedBitmap(wBmp, new Int32Rect( CropLeft, CropTop, (int)(sliceWidth * Width) - CropLeft - CropRight, (int)(sliceHeight * Height) - CropTop - CropBottom)); sw.Stop(); //Console.WriteLine("Grid-sized from {0}x{1} to {2}x{3} in {4}ms.", bmp.Width, bmp.Height, img.PixelWidth, img.PixelHeight, sw.ElapsedMilliseconds); img.Freeze(); _whenProcessed.OnNext(img); return(img); }
// expects the target object as the first parameter, and the resource key as the second public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (values.Length < 2) { return(null); } var element = values[0] as FrameworkElement; var resourceKey = values[1]; if (element == null || resourceKey == null) { return(null); } if (ResourceKeyFormat != null) { resourceKey = string.Format(ResourceKeyFormat, resourceKey); } if (ResourceKeyConverter != null) { resourceKey = ResourceKeyConverter.Convert(resourceKey, targetType, ConverterParameter, culture); } if (resourceKey == null) { return(null); } var resource = element.TryFindResource(resourceKey); if (resource != null) { if (CropRect == null) { return(resource); } else if (resource is BitmapSource) { BitmapSource bitmap = resource as BitmapSource; var result = new CroppedBitmap(bitmap, CropRect); result.Freeze(); return(result); } } string fileName = null; resourceKey = values[1]; if (StringFormat != null) { fileName = string.Format(StringFormat, resourceKey); } if (ResourceKeyConverter != null) { fileName = ResourceKeyConverter.Convert(fileName, targetType, ConverterParameter, culture).ToString(); } if (fileName != null) { fileName = string.Format("pack://siteoforigin:,,,/{0}", fileName); try { object imageObj = (new ImageSourceConverter()).ConvertFromString(fileName); var image = imageObj as ImageSource; if (image != null) { if (CropRect == null) { return(image); } else if (image is BitmapSource) { BitmapSource bitmap = image as BitmapSource; var result = new CroppedBitmap(bitmap, CropRect); result.Freeze(); return(result); } } } catch (NullReferenceException) { } catch (NotSupportedException) { } catch (ArgumentException) { Trace.TraceWarning("Image not in expected size: {0}", fileName); } } Trace.TraceWarning("Resource not found: {0} or {1}\n", resourceKey, fileName); return(null); }