/// <summary> /// Converts a bitmap to a bitmap source. /// </summary> /// <param name="image"> The bitmap. </param> /// <returns> /// The bitmap source. /// </returns> /// <exception cref="ArgumentNullException"> <paramref name="image" /> is null. </exception> public static BitmapSource ToBitmapSource(this Bitmap image) { if (image == null) { throw new ArgumentNullException(nameof(image)); } IntPtr hBitmap = IntPtr.Zero; try { hBitmap = image.GetHbitmap(); BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); return(bitmapSource.Clone()); } finally { if (hBitmap != IntPtr.Zero) { BitmapSourceExtensions.DeleteObject(hBitmap); } } }
public void AddColorFrame(BitmapSource bitmap) { if (this.isRecording) { _Frame frame; TimeSpan timeWithPreviousFrame; DateTime now = DateTime.Now; TimeSpan timeSpan = now.Subtract(this.StartDate); string path = this.GetColorFramePath() + now.GetStringTime() + ".jpg"; if (this.previousFrame == null) { timeWithPreviousFrame = timeSpan; } else { timeWithPreviousFrame = timeSpan.Subtract(this.previousFrame.Time); } frame = new _Frame(bitmap.Clone(), path, timeSpan, timeWithPreviousFrame, _Frame.FrameType.Color); this.previousFrame = frame; frames.Add(frame); //bitmap.ToImageFile(path); } }
public static BitmapSource GetResized(BitmapSource src, int Size) { BitmapSource Source = src.Clone(); BitmapSource backup = Source.Clone(); try { TransformedBitmap scaled = new TransformedBitmap(); scaled.BeginInit(); scaled.Source = Source; double scX = (double)Size / (double)Source.PixelWidth; double scy = (double)Size / (double)Source.PixelHeight; ScaleTransform tr = new ScaleTransform(scX, scy, Source.Width / 2, Source.Height / 2); scaled.Transform = tr; scaled.EndInit(); Source = scaled; } catch { Source = backup; } int stride = ((((Source.Format.BitsPerPixel * Source.PixelWidth) + 31) / 32) * 4); byte[] sourceBuffer = new byte[stride * Source.PixelHeight]; Source.CopyPixels(sourceBuffer, stride, 0); BitmapSource bmp = BitmapSource.Create(Source.PixelWidth, Source.PixelHeight, 96, 96, Source.Format, Source.Palette, sourceBuffer, stride); return(bmp); }
private void Window_MouseMove(object sender, MouseEventArgs e) { if (isDown) { selectRectangle.Visibility = Visibility.Visible; System.Windows.Point point = e.GetPosition(this); double left = Math.Min(frist.X, point.X); double top = Math.Min(frist.Y, point.Y); double w = Math.Abs(frist.X - point.X); double h = Math.Abs(frist.Y - point.Y); selectRectangle.Margin = new Thickness(left, top, 0, 0); selectRectangle.Width = w; selectRectangle.Height = h; selectRectangle.HorizontalAlignment = HorizontalAlignment.Left; selectRectangle.VerticalAlignment = VerticalAlignment.Top; BitmapSource bs = bitmapSource.Clone(); int stride = Convert.ToInt32(bs.Format.BitsPerPixel * w / 8); byte[] data = new byte[(int)h * stride * 4]; try { Int32Rect rect = new Int32Rect((int)left, (int)top, (int)w, (int)h); bs.CopyPixels(rect, data, stride, 0); outImage = BitmapSource.Create((int)w, (int)h, 0, 0, PixelFormats.Bgr32, null, data, stride); selectRectangle.Fill = new ImageBrush(outImage); } catch (Exception) { } } }
/// <summary> /// Converts a bitmap source to a bitmap frame. /// </summary> /// <param name="image"> The bitmap source. </param> /// <returns> /// The bitmap frame. /// </returns> /// <exception cref="ArgumentNullException"> <paramref name="image" /> is null. </exception> public static BitmapFrame ToBitmapFrame(this BitmapSource image) { if (image == null) { throw new ArgumentNullException(nameof(image)); } return(BitmapFrame.Create(image.Clone())); }
public static BitmapSource Copy(this BitmapSource bms) { if (bms.IsNullOrEmpty()) { return(null); } return(bms.Clone()); }
private static void SaveBitmapSource_Delegate() { if (_bCopy) { _savedImages[_imageName] = _bitmapSource.Clone(); } else { _savedImages[_imageName] = _bitmapSource; } }
private void showPreview(BitmapSource bmpSrc) { var bitmapSource = bmpSrc.Clone(); OutputImage oi = new OutputImage(); oi.Owner = this; oi.WindowStartupLocation = WindowStartupLocation.CenterOwner; oi.setOutputImage(bitmapSource); oi.setDestinationPath(destinationPath); oi.ShowDialog(); }
/// <summary> /// Populates the class with the supplied bitmap /// </summary> /// <param name="sourceBitmap">A fully initialized BitmapSource image</param> private void PopulateData(BitmapSource sourceBitmap) { if (sourceBitmap == null) { return; } ClearData( ); _bitmapOriginal = sourceBitmap.Clone( ); _stride = CalculateStride(_bitmapOriginal); CreateByteArraysFromBitmap( ); }
private void SetOutputImage(BitmapSource bitmap) { if (ReferenceEquals(_outputImage, bitmap)) { return; } var copy = bitmap.Clone(); copy.Freeze(); Dispatcher.CurrentDispatcher.Invoke(() => OutputImage = copy); }
public ImageCapture GetScreenshot() { Rect rect = SelectionRectangle0Based; if (rect.Width > 0 && rect.Height > 0) { if (rect.X == 0 && rect.Y == 0 && rect.Width == backgroundImage.Width && rect.Height == backgroundImage.Height) { return(new ImageCapture(backgroundImage.Clone())); } return(new ImageCapture(ImageHelper.CropImage(backgroundImage, rect))); } return(null); }
private void ChangePropertyItems(string path, DateTime newDate, string newCamMan, string newCamModel) { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.Read)) { BitmapSource img = BitmapFrame.Create(fs); Freezable newFreezable = img.Clone(); BitmapSource newImg = (BitmapSource)newFreezable; BitmapMetadata newMd = (BitmapMetadata)newImg.Metadata; newMd.DateTaken = newDate.ToString(); newMd.CameraManufacturer = newCamMan; newMd.CameraModel = newCamModel; fs.Close(); fs.Dispose(); } }
public bool GetImage(out BitmapSource bmpSource, out System.Drawing.Bitmap bmp) { bool result = false; bmp = null; bmpSource = null; try { if (Monitor.TryEnter(imageLock, 5000)) { try { bmp = new System.Drawing.Bitmap(latestBitmap.Width, latestBitmap.Height, latestBitmap.PixelFormat); using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp)) { gr.DrawImage(latestBitmap, new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height)); } bmpSource = latestBitmapSrc.Clone(); bmpSource.Freeze(); result = true; } finally { Monitor.Exit(imageLock); } } else { throw new Exception("timed out waiting for imageLock"); } } catch (Exception ex) { lastError = ex.Message; result = false; } return(result); }
public ImageMetaData(BitmapSource image) #endif { if (image == null) { throw new ArgumentNullException(nameof(image)); } #if GDIPLUS this.image = (Bitmap)image.Clone(); #else this.image = image.Clone(); #endif exifBytes = null; xmpBytes = null; extractedExif = false; extractedXMP = false; disposed = false; }
/// <summary> /// Zastosowanie filtrów jasności, kontrastu i gammy w prostokącie definiowanym przez startPoint i endPoint /// </summary> /// <param name="startPoint">Punkt startowy zaznaczonego obszaru</param> /// <param name="endPoint">Punkt końcowy zaznaczonego obszaru</param> public void ApplyFilters(Point startPoint, Point endPoint) { if (_sourceBitmap == null) { return; } prepareMaps(); var area = new Int32Rect( (int)(_sourceBitmap.PixelWidth * (startPoint.X / 590)), (int)(_sourceBitmap.PixelHeight * (startPoint.Y / 590)), (int)((_sourceBitmap.PixelWidth * (endPoint.X / 590)) - (_sourceBitmap.PixelWidth * (startPoint.X / 590))), (int)((_sourceBitmap.PixelHeight * (endPoint.Y / 590)) - (_sourceBitmap.PixelHeight * (startPoint.Y / 590))) ); var pixelsArrayCopy = new byte[(int)(((_sourceBitmap.PixelWidth * (endPoint.X / 590)) - (_sourceBitmap.PixelWidth * (startPoint.X / 590))) * ((_sourceBitmap.PixelHeight * (endPoint.Y / 590)) - (_sourceBitmap.PixelHeight * (startPoint.Y / 590))))]; _sourceBitmap.CopyPixels(area, pixelsArrayCopy, (int)((_sourceBitmap.PixelWidth * (endPoint.X / 590)) - (_sourceBitmap.PixelWidth * (startPoint.X / 590))), 0); int[] grayColorCount = new int[256]; var arrayLength = pixelsArrayCopy.Length; for (var x = 0; x < arrayLength; x++) { var tmpPixel = (int)pixelsArrayCopy[x]; tmpPixel = brightnessMap[tmpPixel]; tmpPixel = contrastMap[tmpPixel]; pixelsArrayCopy[x] = (byte)gammaMap[tmpPixel]; grayColorCount[tmpPixel] += 1; } var wrBitmap = (WriteableBitmap)(_sourceBitmap.Clone()); wrBitmap.WritePixels(area, pixelsArrayCopy, (int)((_sourceBitmap.PixelWidth * (endPoint.X / 590)) - (_sourceBitmap.PixelWidth * (startPoint.X / 590))), 0); _customizedBitmap = wrBitmap.Clone(); _chartWindow.applyDataToChart(grayColorCount); }
public static BitmapSource GetResized(BitmapSource source, int size) { var backup = source.Clone(); try { var transformedBitmap = new TransformedBitmap(); transformedBitmap.BeginInit(); transformedBitmap.Source = source; var scaleX = size / (double)source.PixelWidth; var scaleY = size / (double)source.PixelHeight; var scaleTransform = new ScaleTransform(scaleX, scaleY, source.Width / 2, source.Height / 2); transformedBitmap.Transform = scaleTransform; transformedBitmap.EndInit(); source = transformedBitmap; } catch { source = backup; } return(source); }
public static BitmapSource GetResized(BitmapSource Source, int Size) { BitmapSource backup = Source.Clone(); try { TransformedBitmap scaled = new TransformedBitmap(); scaled.BeginInit(); scaled.Source = Source; double scX = (double)Size / (double)Source.PixelWidth; double scy = (double)Size / (double)Source.PixelHeight; ScaleTransform tr = new ScaleTransform(scX, scy, Source.Width / 2, Source.Height / 2); scaled.Transform = tr; scaled.EndInit(); Source = scaled; } catch (Exception) { Source = backup; } return(Source); }
private void Canvas_MouseMove(object sender, System.Windows.Input.MouseEventArgs e) { try { if (e.MouseDevice.LeftButton == MouseButtonState.Pressed) { bd.Width = e.GetPosition((IFrameworkInputElement)sender).X - p.X; bd.Height = e.GetPosition((IFrameworkInputElement)sender).Y - p.Y; var p2 = e.GetPosition((IFrameworkInputElement)sender); System.Windows.Controls.Image i = new System.Windows.Controls.Image(); BitmapSource b = screenscource.Clone(); i.Source = b; i.Clip = new RectangleGeometry(); c = new CroppedBitmap(screenscource, new Int32Rect((int)(p.X * rate), (int)(p.Y * rate), (int)(((int)p2.X - (int)p.X) * rate), (int)(((int)p2.Y - (int)p.Y) * rate))); bd.Background = new ImageBrush(c); } } catch (Exception) { } }
public PSFilterHost(BitmapSource sourceImage, System.Windows.Media.Color primary, System.Windows.Media.Color secondary, Region selectedRegion, IntPtr parentWindowHandle) #endif { if (sourceImage == null) { throw new ArgumentNullException(nameof(sourceImage)); } int imageWidth = 0; int imageHeight = 0; #if GDIPLUS imageWidth = sourceImage.Width; imageHeight = sourceImage.Height; #else imageWidth = sourceImage.PixelWidth; imageHeight = sourceImage.PixelHeight; #endif if (imageWidth > 32000 || imageHeight > 32000) { string message = string.Empty; if (imageWidth > 32000 && imageHeight > 32000) { message = Resources.ImageSizeTooLarge; } else { if (imageWidth > 32000) { message = Resources.ImageWidthTooLarge; } else { message = Resources.ImageHeightTooLarge; } } throw new ImageSizeTooLargeException(message); } #if GDIPLUS source = (Bitmap)sourceImage.Clone(); #else source = sourceImage.Clone(); #endif disposed = false; dest = null; filterParameters = null; primaryColor = primary; secondaryColor = secondary; if (selectedRegion != null) { this.selectedRegion = selectedRegion.Clone(); } else { this.selectedRegion = null; } owner = parentWindowHandle; pseudoResources = null; abortFunc = null; hostInfo = null; hostColorProfiles = null; sessionSettings = null; }
public static BitmapSource ScaledCrop(this BitmapSource source, int width, int height, double scale, double x, double y) { var initialSource = Math.Abs(scale - 1) > 0 ? source.ResizedImage((int)(source.Width * scale), (int)(source.Height * scale)) : source.Clone(); try { if (source.Width < width) { var rate = width / source.Width; var newWidth = source.Width * rate; var newHeight = source.Height * rate; initialSource = source.ResizedImage((int)newWidth, (int)newHeight); } else if (source.Height < height) { var rate = height / source.Height; var newWidth = source.Width * rate; var newHeight = source.Height * rate; initialSource = source.ResizedImage((int)newWidth, (int)newHeight); } //get the middle point of the image var posX = x; var posY = y; //if x goes past zero then reset x to 0 if (posX < 0) { posX = 0; } //if y goes past zero then reset y to 0 if (posY < 0) { posY = 0; } //if x makes the width more than the area allows correct x with the difference in widths. if (posX + width > initialSource.Width) { var diff = (int)(posX + width - initialSource.Width); posX -= diff; } //if y makes the height more than the area allows correct y with the difference in widths. if (posY + height > initialSource.Height) { var diff = (int)(posY + height - initialSource.Height); posY -= diff; } return(initialSource.CropAtRect(new Int32Rect((int)posX, (int)posY, width, height))); } catch (Exception) { //if failed just return original image using the crop size from the top left return(initialSource.CropAtRect(new Int32Rect((int)0, (int)0, width, height))); } }
public static BitmapSource ResizeImageAndRatio(this BitmapSource original, double newWidth, double newHeight, double adjustedWidth = 0, double adjustedHeight = 0, double rescale = 1) { //rescale BaseImage var initialSource = Math.Abs(rescale - 1) > 0 ? original.ResizedImage((int)(original.Width * rescale), (int)(original.PixelHeight * rescale)) : original.Clone(); if (Math.Abs(adjustedHeight) > 0 || Math.Abs(adjustedWidth) > 0) { try { //get the middle point of the image var posX = (int)((initialSource.Width - original.Width) / 2 + adjustedWidth); var posY = (int)((initialSource.Height - original.Height) / 2 + adjustedHeight); //if x goes past zero then reset x to 0 if (posX < 0) { posX = 0; } //if y goes past zero then reset y to 0 if (posY < 0) { posY = 0; } //if x makes the width more than the area allows correct x with the difference in widths. if (posX + original.Width > initialSource.Width) { var diff = (int)(posX + original.Width - initialSource.Width); posX -= diff; } //if y makes the height more than the area allows correct y with the difference in widths. if (posY + original.Height > initialSource.Height) { var diff = (int)(posY + original.Height - initialSource.Height); posY -= diff; } initialSource = initialSource.CropAtRect(new Int32Rect(posX, posY, original.PixelWidth, original.PixelHeight)); } catch (Exception) { // ignored, if crop fails because value is out of bounds ignore and reset image initialSource = Math.Abs(rescale - 1) > 0 ? original.ResizedImage((int)(original.Width * rescale), (int)(original.PixelHeight * rescale)) : original.Clone(); } } //build image and destination ratios var destinationRatio = newWidth / newHeight; var baseRatio = initialSource.Width / initialSource.Height; try { //if the ratio are both the same (16:9 == 16:9) // ReSharper disable once CompareOfFloatsByEqualityOperator if (destinationRatio == baseRatio) { return(ScaleImage(initialSource, (int)newWidth, (int)newHeight)); } else { // create a new drawing context to render that changes var drawingVisual = new DrawingVisual(); var drawingContext = drawingVisual.RenderOpen(); //create the source and destination areas to get and put the image var sourceArea = new Rect(0, 0, 0, 0); var destinationArea = new Rect(0, 0, 0, 0); //if the Destination Ratio is larger than the original ratio as the width is larger than the height of the image if (destinationRatio > baseRatio) { // set start position X, Y sourceArea.X = 0; // set the Y axis to start on the point in the image where the height matches the destinations ratio. sourceArea.Y = int.Parse(Math.Floor((initialSource.Height - initialSource.Width / destinationRatio) / 2).ToString(CultureInfo.CurrentCulture)); // set the width to the source sourceArea.Width = initialSource.Width; // set the height to match the base width by the dest. ratio sourceArea.Height = int.Parse(Math.Floor(initialSource.Width / destinationRatio).ToString(CultureInfo.CurrentCulture)); // set the X and Y destinationArea.X = 0; destinationArea.Y = 0; //set the width to base width destinationArea.Width = initialSource.Width; // set the height to match the base width by the dest. ratio destinationArea.Height = int.Parse(Math.Floor(initialSource.Width / destinationRatio).ToString(CultureInfo.CurrentCulture)); } //if the Destination Ratio is lesser than the original ratio as the height is larger than the width of the image else { // set start position X, Y // set the X axis to start on the point in the image where the width matches the destinations ratio. sourceArea.X = int.Parse(Math.Floor((initialSource.Width - initialSource.Height * destinationRatio) / 2).ToString(CultureInfo.CurrentCulture)); sourceArea.Y = 0; // set the width to match the base height by the dest. ratio sourceArea.Width = int.Parse(Math.Floor(initialSource.PixelHeight * destinationRatio).ToString(CultureInfo.CurrentCulture)); // set the width to the source sourceArea.Height = initialSource.Height; // set the X and Y destinationArea.X = 0; destinationArea.Y = 0; // set the width to match the base height by the dest. ratio destinationArea.Width = int.Parse(Math.Floor(initialSource.Height * destinationRatio).ToString(CultureInfo.CurrentCulture)); //set the height to base height destinationArea.Height = initialSource.Height; } //crop from the initial source the area that matches the destinations ratio. var image = initialSource.CropAtRect(new Int32Rect((int)sourceArea.X, (int)sourceArea.Y, (int)sourceArea.Width, (int)sourceArea.Height)); //render the image from the cropped portion using the destination area drawingContext.DrawImage(image, destinationArea); drawingContext.Close(); //use the visual context to render into a bitmap target var bmp = new RenderTargetBitmap((int)destinationArea.Width, (int)destinationArea.Height, initialSource.DpiX, initialSource.DpiY, PixelFormats.Pbgra32); //return rendered image bmp.Render(drawingVisual); return(bmp); } } catch (Exception) { return(null); } }
public override BitmapSource ExecuteFilter(BitmapSource inputImage) { locked = true; BitmapSource blurred = inputImage.Clone(); int pixelCount = inputImage.PixelWidth * inputImage.PixelHeight; int[] b = new int[pixelCount]; int[] g = new int[pixelCount]; int[] r = new int[pixelCount]; int[] b2 = new int[pixelCount]; int[] g2 = new int[pixelCount]; int[] r2 = new int[pixelCount]; int width = inputImage.PixelWidth; int height = inputImage.PixelHeight; byte[] srcPixels = new byte[width * height * 4]; byte[] destPixels = new byte[width * height * 4]; inputImage.CopyPixels(srcPixels, width * 4, 0); blurred.CopyPixels(destPixels, width * 4, 0); for (int i = 0, j = 0; i < pixelCount * 4; i += 4, j++) { b[j] = srcPixels[i]; g[j] = srcPixels[i + 1]; r[j] = srcPixels[i + 2]; } int index = 0; int bsum; int gsum; int rsum; int sum; int read; int start = 0; index = 0; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { bsum = gsum = rsum = sum = 0; read = index - _radius; for (int z = 0; z < _kernel.Length; z++) { if (read >= start && read < start + width) { bsum += _multable[z, b[read]]; gsum += _multable[z, g[read]]; rsum += _multable[z, r[read]]; sum += _kernel[z]; } ++read; } b2[index] = (bsum / sum); g2[index] = (gsum / sum); r2[index] = (rsum / sum); ++index; } start += width; } int tempy; int pixelIndex = 0; for (int i = 0; i < height; i++) { int y = i - _radius; start = y * width; for (int j = 0; j < width; j++) { bsum = gsum = rsum = sum = 0; read = start + j; tempy = y; for (int z = 0; z < _kernel.Length; z++) { if (tempy >= 0 && tempy < height) { bsum += _multable[z, b2[read]]; gsum += _multable[z, g2[read]]; rsum += _multable[z, r2[read]]; sum += _kernel[z]; } read += width; ++tempy; } destPixels[pixelIndex] = (byte)(bsum / sum); destPixels[pixelIndex + 1] = (byte)(gsum / sum); destPixels[pixelIndex + 2] = (byte)(rsum / sum); pixelIndex += 4; } } blurred = BitmapSource.Create(blurred.PixelWidth, blurred.PixelHeight, 96, 96, blurred.Format, null, destPixels, blurred.PixelWidth * 4); locked = false; return(blurred); }