protected override void DrawVisualThumbnail(DrawingContext drawingContext, out string title, ref BitmapSource icon) { var aeroColor = (Color) Application.Current.Resources["AeroColor"]; var aeroBrush = new SolidColorBrush(aeroColor); var aeroPen = new Pen(aeroBrush, 7); var largeIcon = (BitmapSource) Application.Current.Resources["TextClipboardItemIcon"]; var fontFamily = (FontFamily) Application.Current.Resources["CuprumFont"]; var typeface = new Typeface(fontFamily, FontStyles.Normal, FontWeights.Light, FontStretches.Normal); const int textOffset = VisualThumbnailMargin + 51 + VisualThumbnailMargin / 2; var text = new FormattedText(Text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, 15, aeroBrush); text.TextAlignment = TextAlignment.Left; text.MaxTextWidth = VisualThumbnailWidth - textOffset - VisualThumbnailMargin; text.MaxTextHeight = VisualThumbnailHeight - VisualThumbnailMargin * 2; drawingContext.DrawRectangle(Brushes.White, aeroPen, new Rect(-1, -1, VisualThumbnailWidth + 2, VisualThumbnailHeight + 2)); drawingContext.DrawImage(largeIcon, new Rect(VisualThumbnailMargin, VisualThumbnailMargin, 51, 66)); drawingContext.DrawText(text, new Point(textOffset, VisualThumbnailMargin)); title = Text; }
private void CalculateLuminanceRGB(BitmapSource bitmap) { var width = bitmap.PixelWidth; var height = bitmap.PixelHeight; var stepX = (bitmap.Format.BitsPerPixel + 7) / 8; var bufferSize = width * stepX; var buffer = new byte[bufferSize]; var rect = new Int32Rect(0, 0, width, 1); var luminanceIndex = 0; luminances = new byte[width * height]; for (var curY = 0; curY < height; curY++) { bitmap.CopyPixels(rect, buffer, bufferSize, 0); for (var curX = 0; curX < bufferSize; curX += stepX) { var r = buffer[curX]; var g = buffer[curX + 1]; var b = buffer[curX + 2]; luminances[luminanceIndex] = (byte) (0.3 * r + 0.59 * g + 0.11 * b + 0.01); luminanceIndex++; } rect.Y++; } }
protected override void DrawVisualThumbnail(System.Windows.Media.DrawingContext drawingContext, out string title, ref BitmapSource icon) { var aeroColor = (Color)Application.Current.Resources["AeroColor"]; var aeroBrush = new SolidColorBrush(aeroColor); var aeroPen = new Pen(aeroBrush, 7); var grayBrush = new SolidColorBrush(Color.FromArgb(0x70, 255, 255, 255)); var transparencyOverlayBrush = new SolidColorBrush(Color.FromArgb(0x22, 0, 0, 0)); var fontFamily = (FontFamily)Application.Current.Resources["CuprumFont"]; var typeface = new Typeface(fontFamily, FontStyles.Normal, FontWeights.Light, FontStretches.Normal); const int sourceTextOffset = VisualThumbnailMargin + 16 + VisualThumbnailMargin / 2; var sourceText = new FormattedText(Source.ApplicationName ?? "Unknown application", CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, 14, grayBrush); sourceText.MaxTextWidth = VisualThumbnailWidth - sourceTextOffset - VisualThumbnailMargin; sourceText.MaxTextHeight = 32; var imageRectangle = new Rect(-1, -1, VisualThumbnailWidth + 1 * 2, VisualThumbnailHeight + 1 * 2); drawingContext.DrawImage(Image, imageRectangle); drawingContext.DrawRectangle(transparencyOverlayBrush, aeroPen, imageRectangle); drawingContext.DrawImage(Source.Icon, new Rect(VisualThumbnailMargin, VisualThumbnailHeight - VisualThumbnailMargin - 16, 16, 16)); drawingContext.DrawText(sourceText, new Point(sourceTextOffset, VisualThumbnailHeight - VisualThumbnailMargin - 16)); title = "Image from " + Source.ApplicationName; }
protected override void DrawVisualThumbnail(System.Windows.Media.DrawingContext drawingContext, out string title, ref BitmapSource icon) { var aeroColor = (Color)Application.Current.Resources["AeroColor"]; var aeroBrush = new SolidColorBrush(aeroColor); var aeroPen = new Pen(aeroBrush, 7); var grayBrush = new SolidColorBrush(Color.FromArgb(255, 0xaf, 0xaf, 0xaf)); var fontFamily = (FontFamily)Application.Current.Resources["CuprumFont"]; var typeface = new Typeface(fontFamily, FontStyles.Normal, FontWeights.Light, FontStretches.Normal); const int sourceTextOffset = VisualThumbnailMargin; var sourceText = new FormattedText(Name, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, 14, grayBrush); sourceText.MaxTextWidth = VisualThumbnailWidth - sourceTextOffset - VisualThumbnailMargin; sourceText.MaxTextHeight = 32; var imageRectangle = new Rect(VisualThumbnailWidth / 2 - 64 / 2, VisualThumbnailHeight / 2 - 64 / 2, 64, 64); drawingContext.DrawRectangle(Brushes.White, aeroPen, new Rect(-1, -1, VisualThumbnailWidth + 2, VisualThumbnailHeight + 2)); drawingContext.DrawImage(Icon, imageRectangle); drawingContext.DrawText(sourceText, new Point(sourceTextOffset, VisualThumbnailHeight - VisualThumbnailMargin - 16)); title = Name + " from " + Source.ApplicationName; }
/// <summary> /// Initializes a new instance of the <see cref="BitmapSourceLuminanceSource"/> class. /// </summary> /// <param name="bitmap">The bitmap.</param> public BitmapSourceLuminanceSource(BitmapSource bitmap) : base(bitmap.PixelWidth, bitmap.PixelHeight) { switch (bitmap.Format.ToString()) { case "Bgr24": case "Bgr32": CalculateLuminanceBGR(bitmap); break; case "Bgra32": CalculateLuminanceBGRA(bitmap); break; case "Rgb24": CalculateLuminanceRGB(bitmap); break; case "Bgr565": CalculateLuminanceBGR565(bitmap); break; default: // there is no special conversion routine to luminance values // we have to convert the image to a supported format bitmap = new FormatConvertedBitmap(bitmap, PixelFormats.Bgra32, null, 0); CalculateLuminanceBGR(bitmap); break; } }
private void AddDownloadEventHandlers(BitmapSource bitmap) { var bitmapImage = bitmap as BitmapImage; if (bitmapImage != null) { bitmapImage.ImageOpened += BitmapImageOpened; bitmapImage.ImageFailed += BitmapImageFailed; } else { BlendImages(); } }
private void ImageUpdated(BitmapSource bitmap) { var bitmapImage = bitmap as BitmapImage; if (bitmapImage != null) { bitmapImage.ImageOpened += BitmapImageOpened; bitmapImage.ImageFailed += BitmapImageFailed; } else { SwapImages(); } }
/// <summary> /// Converts the input BitmapSource to the Pbgra32 format WriteableBitmap which is internally used by the WriteableBitmapEx. /// </summary> /// <param name="source">The source bitmap.</param> /// <returns></returns> public static WriteableBitmap ConvertToPbgra32Format(BitmapSource source) { // Convert to Pbgra32 if it's a different format if (source.Format == PixelFormats.Pbgra32) { return new WriteableBitmap(source); } var formatedBitmapSource = new FormatConvertedBitmap(); formatedBitmapSource.BeginInit(); formatedBitmapSource.Source = source; formatedBitmapSource.DestinationFormat = PixelFormats.Pbgra32; formatedBitmapSource.EndInit(); return new WriteableBitmap(formatedBitmapSource); }
/// <summary> /// Executes this drop shadow /// filter on the input image and returns the result /// </summary> /// <param name="inputImage">input image</param> /// <returns>Shadow Dropped Image</returns> /// <example> /// <code> /// Image transformed; /// DropShadowFilter dropShadow = new DropShadowFilter(); /// transformed = dropShadow.ExecuteFilter(myImg); /// </code> /// </example> public override BitmapSource ExecuteFilter(BitmapSource inputImage) { int rightMargin = 4; int bottomMargin = 4; //Get the shadow image Assembly asm = Assembly.GetExecutingAssembly(); ResourceManager rm = new ResourceManager("Genetibase.UI.NuGenImageWorks.ExtraFilters.Images", asm); Bitmap shadow = (Bitmap)rm.GetObject("img"); Bitmap fullImage = new Bitmap(inputImage.Width + 6, inputImage.Height + 6); Graphics g = Graphics.FromImage(fullImage); g.DrawImage(inputImage, 0, 0, inputImage.Width, inputImage.Height); GraphicsUnit units = GraphicsUnit.Pixel; //Draw the shadow's right lower corner Point ulCorner = new Point(fullImage.Width - 6, fullImage.Height - 6); Point urCorner = new Point(fullImage.Width, fullImage.Height - 6); Point llCorner = new Point(fullImage.Width - 6, fullImage.Height); Point[] destPara = { ulCorner, urCorner, llCorner }; Rectangle srcRect = new Rectangle(shadow.Width - 6, shadow.Height - 6, 6, 6); g.DrawImage(shadow, destPara, srcRect, units); //Draw the shadow's right hand side ulCorner = new Point(fullImage.Width - 6, bottomMargin); urCorner = new Point(fullImage.Width, bottomMargin); llCorner = new Point(fullImage.Width - 6, fullImage.Height - 6); destPara = new Point[] { ulCorner, urCorner, llCorner }; srcRect = new Rectangle(shadow.Width - 6, 0, 6, shadow.Height - 6); g.DrawImage(shadow, destPara, srcRect, units); //Draw the shadow's bottom hand side ulCorner = new Point(rightMargin, fullImage.Height - 6); urCorner = new Point(fullImage.Width - 6, fullImage.Height - 6); llCorner = new Point(rightMargin, fullImage.Height); destPara = new Point[] { ulCorner, urCorner, llCorner }; srcRect = new Rectangle(0, shadow.Height - 6, shadow.Width - 6, 6); g.DrawImage(shadow, destPara, srcRect, units); return fullImage; }
public static Texture2D CreateTexture2DFromBitmap(Device device, BitmapSource bitmapSource) { // Allocate DataStream to receive the WIC image pixels int stride = bitmapSource.Size.Width * 4; using (var buffer = new SharpDX.DataStream(bitmapSource.Size.Height * stride, true, true)) { // Copy the content of the WIC to the buffer bitmapSource.CopyPixels(stride, buffer); return new SharpDX.Direct3D11.Texture2D(device, new SharpDX.Direct3D11.Texture2DDescription() { Width = bitmapSource.Size.Width, Height = bitmapSource.Size.Height, ArraySize = 1, BindFlags = SharpDX.Direct3D11.BindFlags.ShaderResource, Usage = SharpDX.Direct3D11.ResourceUsage.Immutable, CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None, Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm, MipLevels = 1, OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), }, new SharpDX.DataRectangle(buffer.DataPointer, stride)); } }
private static BitmapDecoder GetDecoder(BitmapSource image, out GifFile gifFile) { gifFile = null; BitmapDecoder decoder = null; Stream stream = null; Uri uri = null; BitmapCreateOptions createOptions = BitmapCreateOptions.None; var bmp = image as BitmapImage; if (bmp != null) { createOptions = bmp.CreateOptions; if (bmp.StreamSource != null) { stream = bmp.StreamSource; } else if (bmp.UriSource != null) { uri = bmp.UriSource; if (bmp.BaseUri != null && !uri.IsAbsoluteUri) { uri = new Uri(bmp.BaseUri, uri); } } } else { BitmapFrame frame = image as BitmapFrame; if (frame != null) { decoder = frame.Decoder; Uri.TryCreate(frame.BaseUri, frame.ToString(), out uri); } } if (decoder == null) { if (stream != null) { stream.Position = 0; decoder = BitmapDecoder.Create(stream, createOptions, BitmapCacheOption.OnLoad); } else if (uri != null && uri.IsAbsoluteUri) { decoder = BitmapDecoder.Create(uri, createOptions, BitmapCacheOption.OnLoad); } } if (decoder is GifBitmapDecoder && !CanReadNativeMetadata(decoder)) { if (stream != null) { stream.Position = 0; gifFile = GifFile.ReadGifFile(stream, true); } else if (uri != null) { gifFile = DecodeGifFile(uri); } else { throw new InvalidOperationException("Can't get URI or Stream from the source. AnimatedSource should be either a BitmapImage, or a BitmapFrame constructed from a URI."); } } if (decoder == null) { throw new InvalidOperationException("Can't get a decoder from the source. AnimatedSource should be either a BitmapImage or a BitmapFrame."); } return(decoder); }
//できた、アルファの問題解消 //画面全体をキャプチャして、そこから目的の領域を切り抜く方法 //メニューの項目を表示した状態もキャプチャできた private static BitmapSource Capture3() { //SystemParameters.VirtualScreenWidthはマルチモニタ環境で使うと意味がある //IntPtr hBitmap = CreateCompatibleBitmap(screenDC, (int)SystemParameters.VirtualScreenWidth, (int)SystemParameters.VirtualScreenHeight); GetClientRect(GetForegroundWindow(), out RECT clientRect);//アクティブウィンドウのクライアント領域Rect取得 int clientWidth = clientRect.Right - clientRect.Left;//実際はtopとleftは必ず0なので、rightとbottomだけでいい int clientHeight = clientRect.Bottom - clientRect.Top; ClientToScreen(GetForegroundWindow(), out POINT ClientLocate);//クライアント領域の左上座標 IntPtr screenDC = GetDC(IntPtr.Zero);//画面全体のDC IntPtr memDC = CreateCompatibleDC(screenDC);//目的のウィンドウ用DC IntPtr hBitmap = CreateCompatibleBitmap(screenDC, clientWidth, clientHeight); SelectObject(memDC, hBitmap); BitBlt(memDC, 0, 0, clientWidth, clientHeight, screenDC, ClientLocate.X, ClientLocate.Y, SRCCOPY); //カーソルの描画 GetCursorPos(out POINT cursorScreenPoint);//画面上でのカーソル位置 int cursorClientX = cursorScreenPoint.X - ClientLocate.X; int cursorClientY = cursorScreenPoint.Y - ClientLocate.Y; IntPtr cursor = GetCursor(); //カーソルの形状が見た目通りにならないことがある //DrawIcon(memDC, mpX, cursorClientY, cursor); //DrawIconEx(memDC, mpX, cursorClientY, cursor, 0, 0, 0, IntPtr.Zero, DI_DEFAULTSIZE); //DrawIconEx(memDC, mpX, cursorClientY, cursor, 0, 0, 0, IntPtr.Zero, DI_NORMAL);//NORMAL以外は表示されなかったり枠がついたりする //VB現在のマウスポインタの種類を取得したいのですが、いくら調べても方法が... - Yahoo!知恵袋 //https://detail.chiebukuro.yahoo.co.jp/qa/question_detail/q1180420296 GetIconInfo(cursor, out ICONINFO iCONINFO); //BitmapSource ibmp = Imaging.CreateBitmapSourceFromHIcon(iCONINFO.hbmColor, new Int32Rect(), BitmapSizeOptions.FromEmptyOptions());//カーソルハンドルが無効エラー var icolor = Imaging.CreateBitmapSourceFromHBitmap(iCONINFO.hbmColor, IntPtr.Zero, new Int32Rect(), BitmapSizeOptions.FromEmptyOptions()); var imask = Imaging.CreateBitmapSourceFromHBitmap(iCONINFO.hbmMask, IntPtr.Zero, new Int32Rect(), BitmapSizeOptions.FromEmptyOptions()); CURSORINFO curInfo = new CURSORINFO(); curInfo.cbSize = Marshal.SizeOf(typeof(CURSORINFO)); GetCursorInfo(out curInfo); //DrawIcon(memDC, mpX, cursorClientY, curInfo.hCursor);//かなり良くなったけど、I型アイコンのとき真っ白になる //DrawIconEx(memDC, mpX, cursorClientY, curInfo.hCursor, 0, 0, 0, IntPtr.Zero, DI_NORMAL);//これでも変わらず // c# - C#-マウスカーソルイメージのキャプチャ //https://python5.com/q/ukmbkppc //これがわかれば解決できそう //カーソルインフォ → コピーアイコン → アイコンインフォのビットマップマスク画像でI型アイコンの元?の画像取得できた IntPtr hicon = CopyIcon(curInfo.hCursor); GetIconInfo(hicon, out ICONINFO icInfo); BitmapSource imask2 = Imaging.CreateBitmapSourceFromHBitmap(icInfo.hbmMask, IntPtr.Zero, new Int32Rect(), BitmapSizeOptions.FromEmptyOptions()); //var icolor2 = Imaging.CreateBitmapSourceFromHBitmap(icInfo.hbmColor, IntPtr.Zero, new Int32Rect(), BitmapSizeOptions.FromEmptyOptions()); IntPtr maskHdc = CreateCompatibleDC(screenDC); //SelectObject(memDC, hBitmap); //IntPtr iconDC = GetDC(icInfo.hbmMask); IntPtr iconDC = GetDC(hicon); //BitBlt(memDC, 0, 0, clientWidth, clientHeight, maskHdc, 0, 32, SRCCOPY); //BitBlt(memDC, 0, 0, clientWidth, clientHeight, maskHdc, 0, 0, SRCINVERT); //BitBlt(memDC, 0, 0, 32, 32, maskHdc, 0, 32, SRCCOPY); //BitBlt(memDC, 0, 0, 32, 32, maskHdc, 0, 0, SRCINVERT); //BitBlt(memDC, 0, 0, clientWidth, clientHeight, iconDC, 0, 32, SRCCOPY); BitBlt(memDC, clientWidth, clientHeight, 32, 32, iconDC, 0, 32, SRCCOPY); //DrawIconEx(memDC, cursorClientX, cursorClientY, hicon, 0, 0, 0, IntPtr.Zero, DI_NORMAL);//カーソル位置に白四角 //DrawIconEx(memDC, 0, 0, hicon, 0, 0, 0, hicon, DI_NORMAL);//左上に白四角 //DrawIconEx(memDC, cursorClientX, cursorClientY, hicon, 32, 32, 0, IntPtr.Zero, DI_NORMAL);//カーソル位置に白四角 //DrawIconEx(memDC, 0, 0, icInfo.hbmMask, 32, 32, 0, hicon, DI_NORMAL); //DrawIconEx(memDC, cursorClientX, cursorClientY, hicon, 0, 0, 0, IntPtr.Zero, DI_COMPAT);//描画なし //DrawIconEx(memDC, cursorClientX, cursorClientY, hicon, 0, 0, 0, IntPtr.Zero, DI_MASK);//カーソル位置に白四角 //DrawIconEx(memDC, cursorClientX, cursorClientY, hicon, 0, 0, 0, IntPtr.Zero, DI_IMAGE);//カーソル位置に白四角 BitmapSource source = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); DeleteObject(iCONINFO.hbmColor); DeleteObject(iCONINFO.hbmMask); DeleteObject(hBitmap); ReleaseDC(IntPtr.Zero, screenDC); ReleaseDC(IntPtr.Zero, memDC); DeleteObject(cursor); DestroyIcon(hicon); ReleaseDC(IntPtr.Zero, maskHdc); ReleaseDC(IntPtr.Zero, iconDC); return source; }
public WriteableBitmap(BitmapSource @source) { _pixels = new int[0]; }
private static void InitAnimationOrImage(Image imageControl) { var controller = GetAnimationController(imageControl); if (controller != null) { controller.Dispose(); } SetAnimationController(imageControl, null); SetIsAnimationLoaded(imageControl, false); BitmapSource source = GetAnimatedSource(imageControl) as BitmapSource; bool isInDesignMode = DesignerProperties.GetIsInDesignMode(imageControl); bool animateInDesignMode = GetAnimateInDesignMode(imageControl); bool shouldAnimate = !isInDesignMode || animateInDesignMode; // For a BitmapImage with a relative UriSource, the loading is deferred until // BaseUri is set. This method will be called again when BaseUri is set. bool isLoadingDeferred = IsLoadingDeferred(source); if (source != null && shouldAnimate && !isLoadingDeferred) { // Case of image being downloaded: retry after download is complete if (source.IsDownloading) { EventHandler handler = null; handler = (sender, args) => { source.DownloadCompleted -= handler; InitAnimationOrImage(imageControl); }; source.DownloadCompleted += handler; imageControl.Source = source; return; } var animation = GetAnimation(imageControl, source); if (animation != null) { if (animation.KeyFrames.Count > 0) { // For some reason, it sometimes throws an exception the first time... the second time it works. TryTwice(() => imageControl.Source = (ImageSource)animation.KeyFrames[0].Value); } else { imageControl.Source = source; } controller = new ImageAnimationController(imageControl, animation, GetAutoStart(imageControl)); SetAnimationController(imageControl, controller); SetIsAnimationLoaded(imageControl, true); imageControl.RaiseEvent(new RoutedEventArgs(AnimationLoadedEvent, imageControl)); return; } } imageControl.Source = source; if (source != null) { SetIsAnimationLoaded(imageControl, true); imageControl.RaiseEvent(new RoutedEventArgs(AnimationLoadedEvent, imageControl)); } }
protected void UpdateImage(double west, double east, double south, double north, BitmapSource bitmap) { currentImageIndex = (currentImageIndex + 1) % 2; var mapImage = (MapImage)Children[currentImageIndex]; mapImage.SetBoundingBox(west, east, south, north); mapImage.Source = bitmap; ImageUpdated(bitmap); }
private void ComputeSinogramValues() { Mouse.OverrideCursor = Cursors.Wait; SquarePaddedImage pi = new SquarePaddedImage(fileName); BitmapSource padImgBmp = pi.SquareImage; List <byte> pixels8Red = pi.Pixels8PaddedRed; List <byte> pixels8Green = pi.Pixels8PaddedGreen; List <byte> pixels8Blue = pi.Pixels8PaddedBlue; SquareWidth = pi.PaddedWidth; SquareHeight = pi.PaddedHeight; int sinogramValuesSize = numberOfAngles * SquareWidth; sinogramWidth = numberOfAngles; sinogramHeight = SquareWidth; // Initialize the sinogram buffer sinogramValues.Clear(); pixels8SinogramRed.Clear(); pixels8SinogramGreen.Clear(); pixels8SinogramBlue.Clear(); for (int i = 0; i < sinogramValuesSize; ++i) { sinogramValues.Add(0.0); pixels8SinogramRed.Add(0); pixels8SinogramGreen.Add(0); pixels8SinogramBlue.Add(0); } byte red, green, blue; double gray; double sum = 0; double maxsum = sum; double angleDegrees; // Compute the maximum value maxsum = SquareWidth * 256; ImageRotation ir = new ImageRotation(); ir.Pixels8OriginalRed = pixels8Red; ir.Pixels8OriginalGreen = pixels8Green; ir.Pixels8OriginalBlue = pixels8Blue; ir.SquareWidth = pi.PaddedWidth; ir.SquareHeight = pi.PaddedHeight; List <byte> pixels8RotatedRed = new List <byte>(); List <byte> pixels8RotatedGreen = new List <byte>(); List <byte> pixels8RotatedBlue = new List <byte>(); int index1, index2; // Populate the sinogram buffer for (int k = 0; k < numberOfAngles; ++k) { angleDegrees = -k; // Just watch the console for large images. // It should go on until 180. Console.Write(k + " "); ir.RotateImage(angleDegrees); pixels8RotatedRed = ir.Pixels8RotatedRed; pixels8RotatedGreen = ir.Pixels8RotatedGreen; pixels8RotatedBlue = ir.Pixels8RotatedBlue; for (int i = 0; i < SquareWidth; ++i) { sum = 0; index1 = i * numberOfAngles + k; for (int j = 0; j < SquareHeight; ++j) { index2 = j * SquareWidth + i; red = pixels8RotatedRed[index2]; green = pixels8RotatedGreen[index2]; blue = pixels8RotatedBlue[index2]; gray = red * 0.3 + green * 0.59 + blue * 0.11; gray /= maxsum; sum += gray; } sinogramValues[index1] = Math.Exp(-sum); } } Mouse.OverrideCursor = null; }
/// <summary> /// /// </summary> private void event_其他程式啟動_選單(List <data_開啟程式> ar) { M.but_用外部程式開啟.Click += (sender, e) => { u_menu_用外部程式開啟.func_open(M.but_用外部程式開啟); }; u_menu_用外部程式開啟.func_add_menu("檔案右鍵選單", null, () => { fun_顯示原生右鍵選單(false); }); u_menu_用外部程式開啟.func_add_menu("開啟檔案位置", null, () => { M.fun_用檔案總管開啟目前圖片(); }); u_menu_用外部程式開啟.func_add_menu("列印", null, () => { try { var pr = new System.Diagnostics.Process(); pr.StartInfo.FileName = M.ar_path[M.int_目前圖片位置];//文件全稱-包括文件後綴 pr.StartInfo.CreateNoWindow = true; pr.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; pr.StartInfo.Verb = "Print"; pr.Start(); } catch (Exception e2) { MessageBox.Show("找不到對應開啟的程式:\n" + e2.ToString(), "列印失敗"); } }); u_menu_用外部程式開啟.func_add_menu("設成桌布", null, () => { if (File.Exists(M.ar_path[M.int_目前圖片位置])) //判別檔案是否存在於對應的路徑 { try { SystemParametersInfo(20, 1, M.ar_path[M.int_目前圖片位置], 0x1 | 0x2); //存在成立,修改桌布 (uActuin 20 參數為修改wallpaper } catch (Exception e2) { MessageBox.Show("設定桌布失敗:\n" + e2.ToString(), "失敗"); } } }); u_menu_用外部程式開啟.func_add_menu("選擇其他程式", null, () => { if (File.Exists(M.ar_path[M.int_目前圖片位置])) //判別檔案是否存在於對應的路徑 { try { String _path = M.ar_path[M.int_目前圖片位置]; Process.Start(new ProcessStartInfo("rundll32.exe") { Arguments = $"shell32.dll,OpenAs_RunDLL {_path}", WorkingDirectory = Path.GetDirectoryName(_path) }); } catch (Exception e2) { MessageBox.Show(e2.ToString(), "Error"); } } }); u_menu_用外部程式開啟.func_add_水平線(); if (C_window_AERO.IsWindows10()) { // 3D小畫家 String s_Paint3D = M.fun_執行檔路徑() + "/data/imgs/icon-Paint3D.png"; u_menu_用外部程式開啟.func_add_menu_imgPath("3D小畫家", s_Paint3D, () => { if (File.Exists(M.ar_path[M.int_目前圖片位置])) //判別檔案是否存在於對應的路徑 { try { System.Diagnostics.Process.Start("mspaint", '"' + M.ar_path[M.int_目前圖片位置] + '"' + " /ForceBootstrapPaint3D"); } catch (Exception e2) { MessageBox.Show(e2.ToString(), "失敗"); } } }); // win10相片 APP String s_photos = M.fun_執行檔路徑() + "/data/imgs/icon-photos.png"; u_menu_用外部程式開啟.func_add_menu_imgPath("相片 APP", s_photos, () => { if (File.Exists(M.ar_path[M.int_目前圖片位置])) //判別檔案是否存在於對應的路徑 { try { String url_path = Uri.EscapeDataString(M.ar_path[M.int_目前圖片位置]); System.Diagnostics.Process.Start("ms-photos:viewer?fileName=" + url_path); } catch (Exception e2) { MessageBox.Show(e2.ToString(), "失敗"); } } }); } //使用者自定的名單 for (int i = 0; i < ar.Count; i++) { int xx = i; BitmapSource img = null; try { img = M.c_影像.BitmapToBitmapSource(ar[i].img); } catch { } u_menu_用外部程式開啟.func_add_menu(ar[i].name, img, () => { try { System.Diagnostics.Process.Start(ar[xx].path, "\"" + M.ar_path[M.int_目前圖片位置] + "\""); } catch (Exception e2) { MessageBox.Show(e2.ToString()); } }); }//for }
public PrintBase(BitmapSource photo, PrintType printtype, int quantity) { Photo = photo; PrintType = printtype; Quantity = quantity; }
static public ICaptureProcessor createCaptureProcessor(string a_FilePath) { if (MainWindow.mCaptureManager == null) { return(null); } string lPresentationDescriptor = "<?xml version='1.0' encoding='UTF-8'?>" + "<PresentationDescriptor StreamCount='1'>" + "<PresentationDescriptor.Attributes Title='Attributes of Presentation'>" + "<Attribute Name='MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK' GUID='{58F0AAD8-22BF-4F8A-BB3D-D2C4978C6E2F}' Title='The symbolic link for a video capture driver.' Description='Contains the unique symbolic link for a video capture driver.'>" + "<SingleValue Value='ImageCaptureProcessor' />" + "</Attribute>" + "<Attribute Name='MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME' GUID='{60D0E559-52F8-4FA2-BBCE-ACDB34A8EC01}' Title='The display name for a device.' Description='The display name is a human-readable string, suitable for display in a user interface.'>" + "<SingleValue Value='Image Capture Processor' />" + "</Attribute>" + "</PresentationDescriptor.Attributes>" + "<StreamDescriptor Index='0' MajorType='MFMediaType_Video' MajorTypeGUID='{73646976-0000-0010-8000-00AA00389B71}'>" + "<MediaTypes TypeCount='1'>" + "<MediaType Index='0'>" + "<MediaTypeItem Name='MF_MT_FRAME_SIZE' GUID='{1652C33D-D6B2-4012-B834-72030849A37D}' Title='Width and height of the video frame.' Description='Width and height of a video frame, in pixels.'>" + "<Value.ValueParts>" + "<ValuePart Title='Width' Value='Temp_Width' />" + "<ValuePart Title='Height' Value='Temp_Height' />" + "</Value.ValueParts>" + "</MediaTypeItem>" + "<MediaTypeItem Name='MF_MT_AVG_BITRATE' GUID='{20332624-FB0D-4D9E-BD0D-CBF6786C102E}' Title='Approximate data rate of the video stream.' Description='Approximate data rate of the video stream, in bits per second, for a video media type.'>" + "<SingleValue Value='33570816' />" + "</MediaTypeItem>" + "<MediaTypeItem Name='MF_MT_MAJOR_TYPE' GUID='{48EBA18E-F8C9-4687-BF11-0A74C9F96A8F}' Title='Major type GUID for a media type.' Description='The major type defines the overall category of the media data.'>" + "<SingleValue Value='MFMediaType_Video' GUID='{73646976-0000-0010-8000-00AA00389B71}' />" + "</MediaTypeItem>" + "<MediaTypeItem Name='MF_MT_DEFAULT_STRIDE' GUID='{644B4E48-1E02-4516-B0EB-C01CA9D49AC6}' Title='Default surface stride.' Description='Default surface stride, for an uncompressed video media type. Stride is the number of bytes needed to go from one row of pixels to the next.'>" + "<SingleValue Value='Temp_Stride' />" + "</MediaTypeItem>" + "<MediaTypeItem Name='MF_MT_FIXED_SIZE_SAMPLES' GUID='{B8EBEFAF-B718-4E04-B0A9-116775E3321B}' Title='The fixed size of samples in stream.' Description='Specifies for a media type whether the samples have a fixed size.'>" + "<SingleValue Value='True' />" + "</MediaTypeItem>" + "<MediaTypeItem Name='MF_MT_FRAME_RATE' GUID='{C459A2E8-3D2C-4E44-B132-FEE5156C7BB0}' Title='Frame rate.' Description='Frame rate of a video media type, in frames per second.'>" + "<RatioValue Value='10.0'>" + "<Value.ValueParts>" + "<ValuePart Title='Numerator' Value='10' />" + "<ValuePart Title='Denominator' Value='1' />" + "</Value.ValueParts>" + "</RatioValue>" + "</MediaTypeItem>" + "<MediaTypeItem Name='MF_MT_PIXEL_ASPECT_RATIO' GUID='{C6376A1E-8D0A-4027-BE45-6D9A0AD39BB6}' Title='Pixel aspect ratio.' Description='Pixel aspect ratio for a video media type.'>" + "<RatioValue Value='1'>" + "<Value.ValueParts>" + "<ValuePart Title='Numerator' Value='1' />" + "<ValuePart Title='Denominator' Value='1' />" + "</Value.ValueParts>" + "</RatioValue>" + "</MediaTypeItem>" + "<MediaTypeItem Name='MF_MT_ALL_SAMPLES_INDEPENDENT' GUID='{C9173739-5E56-461C-B713-46FB995CB95F}' Title='Independent of samples.' Description='Specifies for a media type whether each sample is independent of the other samples in the stream.'>" + "<SingleValue Value='True' />" + "</MediaTypeItem>" + "<MediaTypeItem Name='MF_MT_SAMPLE_SIZE' GUID='{DAD3AB78-1990-408B-BCE2-EBA673DACC10}' Title='The fixed size of each sample in stream.' Description='Specifies the size of each sample, in bytes, in a media type.'>" + "<SingleValue Value='Temp_SampleSize' />" + "</MediaTypeItem>" + "<MediaTypeItem Name='MF_MT_INTERLACE_MODE' GUID='{E2724BB8-E676-4806-B4B2-A8D6EFB44CCD}' Title='Describes how the frames are interlaced.' Description='Describes how the frames in a video media type are interlaced.'>" + "<SingleValue Value='MFVideoInterlace_Progressive' />" + "</MediaTypeItem>" + "<MediaTypeItem Name='MF_MT_SUBTYPE' GUID='{F7E34C9A-42E8-4714-B74B-CB29D72C35E5}' Title='Subtype GUID for a media type.' Description='The subtype GUID defines a specific media format type within a major type.'>" + "<SingleValue GUID='{Temp_SubTypeGUID}' />" + "</MediaTypeItem>" + "</MediaType>" + "</MediaTypes>" + "</StreamDescriptor>" + "</PresentationDescriptor>"; ImageCaptureProcessor lICaptureProcessor = new ImageCaptureProcessor(); using (var lImageStream = File.Open(a_FilePath, FileMode.Open)) { if (lImageStream == null) { return(null); } var lBitmap = BitmapDecoder.Create(lImageStream, BitmapCreateOptions.None, BitmapCacheOption.None); if (lBitmap == null) { return(null); } if (lBitmap.Frames == null || lBitmap.Frames.Count == 0) { return(null); } BitmapSource bitmapSource = lBitmap.Frames[0]; int lStride = 0; Guid lMFVideoFormat_RGBFormat = MFVideoFormat_ARGB32; MainWindow.mCaptureManager.getStrideForBitmapInfoHeader(lMFVideoFormat_RGBFormat, (uint)bitmapSource.PixelWidth, out lStride); int width = bitmapSource.PixelWidth; int height = bitmapSource.PixelHeight; int stride = (int)Math.Abs(lStride); lPresentationDescriptor = lPresentationDescriptor.Replace("Temp_Width", ((uint)bitmapSource.PixelWidth).ToString()); lPresentationDescriptor = lPresentationDescriptor.Replace("Temp_Height", ((uint)bitmapSource.PixelHeight).ToString()); lPresentationDescriptor = lPresentationDescriptor.Replace("Temp_Stride", lStride.ToString()); lPresentationDescriptor = lPresentationDescriptor.Replace("Temp_SampleSize", ((uint)(Math.Abs(lStride) * bitmapSource.PixelHeight * 3)).ToString()); lPresentationDescriptor = lPresentationDescriptor.Replace("Temp_SubTypeGUID", lMFVideoFormat_RGBFormat.ToString()); lICaptureProcessor.mPresentationDescriptor = lPresentationDescriptor; foreach (var litem in lBitmap.Frames) { bitmapSource = litem; if (bitmapSource.Format != System.Windows.Media.PixelFormats.Bgra32) { FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap(); newFormatedBitmapSource.BeginInit(); newFormatedBitmapSource.Source = litem; newFormatedBitmapSource.DestinationFormat = System.Windows.Media.PixelFormats.Bgra32; newFormatedBitmapSource.EndInit(); bitmapSource = newFormatedBitmapSource; } byte[] lPixels = new byte[height * stride]; bitmapSource.CopyPixels(lPixels, stride, 0); lICaptureProcessor.mRawDataFrames.Add(new RawDataFrame(lPixels)); } } return(lICaptureProcessor); }
public ImageCapture(BitmapSource img) : this() { Source = img; }
public ImageCaptureEventArgs(BitmapSource image) { Image = image; }
void PasteImage_Executed(object sender, ExecutedRoutedEventArgs args) { if (sender == this) { if (Clipboard.ContainsImage()) { BitmapSource src = Clipboard.GetImage(); if (src != null) { try { // find and/or create the folder string folder = Kaxaml.Properties.Settings.Default.PasteImageFolder; string absfolder = ""; if (!folder.Contains(":")) { absfolder = System.IO.Path.Combine(DocumentsView.SelectedDocument.Folder, folder); } else { absfolder = folder; } // create the folder if it doesn't exist if (!System.IO.Directory.Exists(absfolder)) { System.IO.Directory.CreateDirectory(absfolder); } // create a unique filename string filename = Kaxaml.Properties.Settings.Default.PasteImageFile; string tempfile = System.IO.Path.Combine(absfolder, filename); int number = 1; string absfilename = tempfile.Replace("$number$", number.ToString()); while (System.IO.File.Exists(absfilename)) { number++; absfilename = tempfile.Replace("$number$", number.ToString()); } // save the image from the clipboard using (System.IO.FileStream fs = new System.IO.FileStream(absfilename, System.IO.FileMode.Create)) { JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.QualityLevel = 100; //PngBitmapEncoder encoder = new PngBitmapEncoder(); //encoder.Interlace = PngInterlaceOption.Off; encoder.Frames.Add(BitmapFrame.Create(src)); encoder.Save(fs); } // get a relative version of the file name string rfilename = absfilename.Replace(DocumentsView.SelectedDocument.Folder + "\\", ""); // create and insert the xaml string xaml = Kaxaml.Properties.Settings.Default.PasteImageXaml; xaml = xaml.Replace("$source$", rfilename); this.DocumentsView.SelectedView.TextEditor.InsertStringAtCaret(xaml); } catch (Exception ex) { if (ex.IsCriticalException()) { throw; } } } } } }
public PrintBase(BitmapSource photo, string description, double cost) { Photo = photo; PrintType = new PrintType(description, cost); Quantity = 0; }
private static DataStream GetPixels(BitmapSource source, int stride) { var pixels = new DataStream(source.Size.Height * stride, true, true); source.CopyPixels(stride, pixels); return pixels; }
private void DrawCanvas4() { int width = (int)_canvas4.ActualWidth; int height = (int)_canvas4.ActualHeight; using (var bitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb)) using (var graphics = System.Drawing.Graphics.FromImage(bitmap)) { // GDI Bitmap にポリゴンを描画 foreach (var area in _areas) { var points = area.Points; var polygon = new System.Drawing.Point[points.Count]; for (int i = 0; i < points.Count; i++) { var point = points[i]; polygon[i] = new System.Drawing.Point((int)point.X, (int)point.Y); } graphics.FillPolygon(area.FillGdiBrush, polygon); } // GDI Bitmap → ByteArray var rect = new System.Drawing.Rectangle(0, 0, width, height); var bitmapData = bitmap.LockBits( rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); var byteArray = new byte[width * height]; unsafe { var pSrc = (byte *)bitmapData.Scan0.ToPointer(); fixed(byte *pDst = byteArray) { for (int i = 0; i < height; i++) { int srcLine = bitmapData.Stride * i; int dstLine = width * i; for (int j = 0; j < width; j++) { int src = srcLine + (j * 4); int b = pSrc[src]; int g = pSrc[src + 1]; int r = pSrc[src + 2]; //int a = pSrc[src + 3]; int color; if (b != 0) { color = (1 << 6) | 0x3F; } else if (g != 0) { color = (2 << 6) | 0x3F; } else if (r != 0) { color = (3 << 6) | 0x3F; } else { color = 0; } int dst = dstLine + j; pDst[dst] = (byte)color; } } } } bitmap.UnlockBits(bitmapData); // ByteArray → WPF Gray8 var bitmapSource = BitmapSource.Create(width, height, 96, 96, PixelFormats.Gray8, null, byteArray, width); _image4.Source = bitmapSource; } }
private static FormatConverter Convert(ImagingFactory factory, BitmapSource source) { var formatConverter = new FormatConverter(factory); formatConverter.Initialize(source, PixelFormat.Format32bppPRGBA, BitmapDitherType.None, null, 0.0, BitmapPaletteType.Custom); return formatConverter; }
public void GenerateBitmapSources(System.Drawing.Bitmap b) { BitmapSource bsource = Helper.BitmapHelper.GetBitmapSource(b); BitmapSources.Add(bsource); }
/// <summary> /// Conversion from BitmapSource to XImage. /// </summary> public static XImage FromBitmapSource(BitmapSource image) { return new XImage(image); }
private void WebClient_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e) { BitmapSource image = Handlers.ByteToBitmapSource(e.Result); MainWindow.image1.Source = image; }
/// <summary> /// Converts an image to ASCII art /// </summary> /// <param name="source">The original image as System.Windows.Media.Imaging.BitmapSource.</param> /// <param name="progress">Provider for progress updates.</param> /// <returns>A System.Threading.Tasks.Task that represents the conversion operation. The Task's result holds the converted image.</returns> public Task <T> ConvertAsync(BitmapSource source, IProgress <double> progress) { source.Freeze(); return(Task.Factory.StartNew(() => Convert(source, progress))); }
public static BitmapSource DrawFaces(BitmapSource baseImage, FaceAPI.Models.DetectedFace[] faces, string[] celebName) { if (faces == null) { return(baseImage); } Action <DrawingContext, double> drawAction = (drawingContext, annotationScale) => { for (int i = 0; i < faces.Length; i++) { var face = faces[i]; if (face.FaceRectangle == null) { continue; } Rect faceRect = new Rect( face.FaceRectangle.Left, face.FaceRectangle.Top, face.FaceRectangle.Width, face.FaceRectangle.Height); var summary = new StringBuilder(); if (face.FaceAttributes != null) { summary.Append(Aggregation.SummarizeFaceAttributes(face.FaceAttributes)); if (face.FaceAttributes.Emotion != null) { summary.Append(Aggregation.SummarizeEmotion(face.FaceAttributes.Emotion)); } } if (celebName?[i] != null) { summary.Append(celebName[i]); } faceRect.Inflate(6 * annotationScale, 6 * annotationScale); double lineThickness = 4 * annotationScale; drawingContext.DrawRectangle( Brushes.Transparent, new Pen(s_lineBrush, lineThickness), faceRect); if (summary.Length > 0) { FormattedText ft = new FormattedText(summary.ToString(), CultureInfo.CurrentCulture, FlowDirection.LeftToRight, s_typeface, 16 * annotationScale, Brushes.Black); var pad = 3 * annotationScale; var ypad = pad; var xpad = pad + 4 * annotationScale; var origin = new System.Windows.Point( faceRect.Left + xpad - lineThickness / 2, faceRect.Top - ft.Height - ypad + lineThickness / 2); var rect = ft.BuildHighlightGeometry(origin).GetRenderBounds(null); rect.Inflate(xpad, ypad); drawingContext.DrawRectangle(s_lineBrush, null, rect); drawingContext.DrawText(ft, origin); } } }; return(DrawOverlay(baseImage, drawAction)); }
public ImageProcessing(BitmapSource source) { _img = ConvertToBitmap(source); }
/// <summary> /// k平均法を使ってパレットを作成して減色 /// 色の距離はRGB各色の差の2乗を足したのを√ /// </summary> /// <param name="source">PixelFormatPbgra32のBitmapSource</param> /// <param name="colorCount">パレットの色数</param> /// <param name="colorDiff">新旧パレットの色差がこの値を下回ったらパレット完成とする値 /// 小さいほど時間がかかる、0から255、1から5が適度</param> /// <returns>PixelFormatPbgra32のBitmapSource</returns> private BitmapSource ReduceColor減色(BitmapSource source, int colorCount, double colorDiff = 5) { string neko = "start" + "\n";//色と色差の変化の確認用 var wb = new WriteableBitmap(source); int h = wb.PixelHeight; int w = wb.PixelWidth; int stride = wb.BackBufferStride; byte[] pixles = new byte[h * stride]; wb.CopyPixels(pixles, stride, 0); long p = 0; Color myColor; int pIndex; //パレットのインデックス double distance, min, diff = 0; //色の距離、最小値、新旧色の距離 //パレット Color[] palette = GetRandomColorPalette(colorCount); for (int i = 0; i < palette.Length; ++i) { neko += palette[i].ToString() + "\n"; } //グループ分けした色を入れる色List //List<Color>[] colorList = new List<Color>[palette.Length]; List <Color>[] colorList = new List <Color> [palette.Length]; for (int i = 0; i < colorList.Length; ++i) { colorList[i] = new List <Color>(); } for (int j = 0; j < 100; ++j) { //色List作成(初期化) for (int i = 0; i < palette.Length; ++i) { //colorList[i] = new List<Color>(); colorList[i].Clear(); } //ピクセル数が50000未満の画像なら全ピクセルをグループ分け //以上ならランダムで50000ピクセルを取り出してグループ分け if (h * w < 50000) { for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { p = y * stride + (x * 4); myColor = Color.FromRgb(pixles[p + 2], pixles[p + 1], pixles[p]); //グループ分け ColorGrouping(palette, myColor, colorList); } } } else { //50000 Random random = new Random(); for (int k = 0; k < 50000; ++k) { p = (random.Next(h) * stride) + (random.Next(w) * 4); myColor = Color.FromRgb(pixles[p + 2], pixles[p + 1], pixles[p]); //グループ分け ColorGrouping(palette, myColor, colorList); } } //グループ分けした色の平均色から新しいパレット作成 Color[] newPalette = new Color[palette.Length]; for (int i = 0; i < newPalette.Length; ++i) { myColor = GetAverageGolor(colorList[i]);//平均色取得(新しい色) neko += myColor.ToString() + "\n"; diff += GetColorDistance(palette[i], myColor); palette[i] = myColor;//新しい色で上書き } //古いパレットと新しいパレットの色の差が1以下ならループ抜け、新パレット完成 TextBlockLoopCount.Text = "ループ回数 = " + j.ToString(); diff /= palette.Length; neko += diff.ToString() + "\n"; if (diff < colorDiff) { break; } diff = 0; } //パレットの色表示 for (int i = 0; i < palette.Length; ++i) { MyPalette[i].Background = new SolidColorBrush(palette[i]); } Console.WriteLine(neko); //パレットの色で減色 for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { p = y * stride + (x * 4); myColor = Color.FromRgb(pixles[p + 2], pixles[p + 1], pixles[p]); min = GetColorDistance(myColor, palette[0]); pIndex = 0; for (int i = 0; i < palette.Length; ++i) { distance = GetColorDistance(myColor, palette[i]); if (min > distance) { min = distance; pIndex = i; } } myColor = palette[pIndex]; pixles[p + 2] = myColor.R; pixles[p + 1] = myColor.G; pixles[p] = myColor.B; } } wb.WritePixels(new Int32Rect(0, 0, w, h), pixles, stride, 0); PixelFormat pixelFormat; if (colorCount <= 2) { pixelFormat = PixelFormats.Indexed1; } else if (colorCount <= 4) { pixelFormat = PixelFormats.Indexed2; } else if (colorCount <= 16) { pixelFormat = PixelFormats.Indexed4; } else if (colorCount <= 256) { pixelFormat = PixelFormats.Indexed8; } else { pixelFormat = PixelFormats.Bgr24; } return(new FormatConvertedBitmap(wb, pixelFormat, null, 0)); }
public static void Save(this BitmapSource bmp, string path) => BitmapSourceConverter.ToMat(bmp).Save(path);
public SceneRenderProgress(int percentComplete, BitmapSource renderedBitmap) { PercentComplete = percentComplete; RenderedBitmap = renderedBitmap; }
private static ObjectAnimationUsingKeyFrames GetAnimation(Image imageControl, BitmapSource source) { var animation = AnimationCache.GetAnimation(source, GetRepeatBehavior(imageControl)); if (animation != null) { return(animation); } GifFile gifMetadata; var decoder = GetDecoder(source, out gifMetadata) as GifBitmapDecoder; if (decoder != null && decoder.Frames.Count > 1) { var fullSize = GetFullSize(decoder, gifMetadata); int index = 0; animation = new ObjectAnimationUsingKeyFrames(); var totalDuration = TimeSpan.Zero; BitmapSource baseFrame = null; foreach (var rawFrame in decoder.Frames) { var metadata = GetFrameMetadata(decoder, gifMetadata, index); var frame = MakeFrame(fullSize, rawFrame, metadata, baseFrame); var keyFrame = new DiscreteObjectKeyFrame(frame, totalDuration); animation.KeyFrames.Add(keyFrame); totalDuration += metadata.Delay; switch (metadata.DisposalMethod) { case FrameDisposalMethod.None: case FrameDisposalMethod.DoNotDispose: baseFrame = frame; break; case FrameDisposalMethod.RestoreBackground: if (IsFullFrame(metadata, fullSize)) { baseFrame = null; } else { baseFrame = ClearArea(frame, metadata); } break; case FrameDisposalMethod.RestorePrevious: // Reuse same base frame break; } index++; } animation.Duration = totalDuration; animation.RepeatBehavior = GetActualRepeatBehavior(imageControl, decoder, gifMetadata); AnimationCache.AddAnimation(source, GetRepeatBehavior(imageControl), animation); AnimationCache.IncrementReferenceCount(source, GetRepeatBehavior(imageControl)); return(animation); } return(null); }
public void StoreImage() { defaultImg = (BitmapSource)capturedImg.Source; }
/// <param name="baseUrl">Atskaņojamās plūsmas adreses sākumdaļa (ar slīpsvītru galā).</param> public SegmentedChannel(string url, BitmapSource logo, TimeZoneInfo timezone, bool hasGuide, Brand brand, Menu <Channel> menu = null) : base(new SegmentedStream(url), logo, timezone, hasGuide, brand, menu) { }
unsafe void InitializeFont(GDIFont font) { IntPtr hdc = myTempGraphics.GetHdc(); IntPtr hfont = font.ToHfont(); SelectObject(hdc, hfont); if (!GetCharWidth32(hdc, 0, 255, CharacterWidths)) throw new SystemException("Unable to measure character widths."); tagTEXTMETRIC metrics = new tagTEXTMETRIC(); GetTextMetrics(hdc, ref metrics); myLeadingSpace = metrics.tmInternalLeading; myTrailingSpace = metrics.tmExternalLeading; myTempGraphics.ReleaseHdc(hdc); int width = 0; for (int i = myFirstCharacterOfInterest; i <= myLastCharacterOfInterest; i++) { CharacterWidths[i] += myLeadingSpace + myTrailingSpace; width += CharacterWidths[i]; } myHeight = (int)Math.Round(myTempGraphics.MeasureString(myCharactersOfInterest, font).Height); int squareDim = (int)Math.Ceiling(Math.Sqrt(width * myHeight)); squareDim = BitmapSource.GetValidTextureDimensionFromSize(squareDim); int squareWidth = squareDim; int squareHeight = squareDim; float fSquareWidth = squareWidth; float fSquareHeight = squareHeight; Bitmap bitmap; bool fit; do { bitmap = new Bitmap(squareWidth, squareHeight, System.Drawing.Imaging.PixelFormat.Format16bppRgb565); using (Graphics g = Graphics.FromImage(bitmap)) { int x = 0; int y = 0; for (char i = myFirstCharacterOfInterest; i <= myLastCharacterOfInterest; i++) { if (x + CharacterWidths[i] >= fSquareWidth) { y += myHeight; x = 0; } CharacterLocations[i] = new Point(x, y); float uStart = x / fSquareWidth; float uEnd = (x + CharacterWidths[i]) / fSquareWidth; float vStart = y / fSquareHeight; float vEnd = (y + myHeight) / fSquareHeight; int offset = i * 4; TextureCoordinates[offset] = new TextureCoordinate(uStart, vEnd); TextureCoordinates[offset+ 1] = new TextureCoordinate(uStart, vStart); TextureCoordinates[offset + 2] = new TextureCoordinate(uEnd, vEnd); TextureCoordinates[offset + 3] = new TextureCoordinate(uEnd, vStart); g.DrawString(i.ToString(), font, myWhiteBrush, x, y); // adding a 1 pixel extra margin on the left seems to clear up some artifacting // that occurs as a result of glyphs being too close together. x += CharacterWidths[i] + 1; } fit = y + myHeight < fSquareHeight; if (!fit) { squareWidth <<= 1; fSquareWidth = squareWidth; } } } while (!fit); byte[] alphaBytes = new byte[bitmap.Width * bitmap.Height]; BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format16bppRgb565); int pixCount = 0; for (int y = 0; y < bitmap.Height; y++) { short* yp = (short*)((int)data.Scan0 + data.Stride * y); for (int x = 0; x < bitmap.Width; x++, pixCount++) { short* p = (short*)(yp + x); short pixel = *p; byte b = (byte)((pixel & 0x1F) << 3); byte g = (byte)(((pixel >> 5) & 0x3F) << 2); byte r = (byte)(((pixel >> 11) & 0x1F) << 3); byte totalAlpha = (byte)((r + g + b) / 3); alphaBytes[pixCount] = totalAlpha; } } bitmap.UnlockBits(data); bitmap.Dispose(); uint tex = 0; gl.GenTextures(1, &tex); gl.BindTexture(gl.GL_TEXTURE_2D, tex); fixed (byte* alphaBytesPointer = alphaBytes) { gl.TexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_ALPHA, squareWidth, squareHeight, 0, gl.GL_ALPHA, gl.GL_UNSIGNED_BYTE, (IntPtr)alphaBytesPointer); } gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR); gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR); gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE); gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE); mySource = new BitmapSource(); mySource.myWidth = squareWidth; mySource.myHeight = squareHeight; mySource.myName = tex; mySource.myIsTransparent = true; }
//Bgra32とスケーリングしている場合は?ホットスポット? private BitmapSource MixBitmap(BitmapSource source, BitmapSource cursor, POINT cursorLocate, int xOffset, int yOffset) { BitmapSource resultBmp = null; int sideLenght = cursor.PixelWidth;//32、横一辺の長さ int maskHeight = cursor.PixelHeight;//64、縦は横の2倍のはず if (sideLenght * 2 != maskHeight) return resultBmp;//2倍じゃなければnullを返して終了 //マスク画像を上下半分に切り出して画素値を配列化、マスク画像は白と黒の2色の1bpp画像のはず //ピクセルフォーマットをbgra32に変換して計算しやすくする BitmapSource maskBmp1 = new CroppedBitmap(cursor, new Int32Rect(0, 0, sideLenght, sideLenght)); FormatConvertedBitmap m1 = new FormatConvertedBitmap(maskBmp1, PixelFormats.Bgra32, null, 0); //var m11 = new FormatConvertedBitmap(maskBmp1, PixelFormats.Bgr24, null, 0); int maskStride = (m1.PixelWidth * 32 + 7) / 8; byte[] mask1Pixels = new byte[m1.PixelHeight * maskStride]; m1.CopyPixels(mask1Pixels, maskStride, 0); BitmapSource maskBmp2 = new CroppedBitmap(cursor, new Int32Rect(0, sideLenght, sideLenght, sideLenght)); var m2 = new FormatConvertedBitmap(maskBmp2, PixelFormats.Bgra32, null, 0); byte[] mask2Pixels = new byte[m2.PixelHeight * maskStride]; m2.CopyPixels(mask2Pixels, maskStride, 0); int w = source.PixelWidth; int h = source.PixelHeight; int bpp = source.Format.BitsPerPixel;//1ビクセルあたりのbit数、bgra32は4になるはず int stride = (w * bpp + 7) / 8; byte[] pixels = new byte[h * stride]; source.CopyPixels(pixels, stride, 0); int beginX = cursorLocate.X - xOffset; int beginY = cursorLocate.Y - yOffset; int endX = beginX + sideLenght; int endY = beginY + sideLenght; if (endX > w) endX = w; if (endY > h) endY = h; int yCount = 0; int xCount = 0; int nekocount = 0; for (int y = beginY; y < endY; y++) { for (int x = beginX; x < endX; x++) { var p = y * stride + x * 4; var pp = yCount * maskStride + xCount * 4; //pixels[p] = 0; //pixels[p+1] = 0; //pixels[p+2] = 0; //マスク1が黒なら画像も黒にする if (mask1Pixels[pp] == 0) { pixels[p] = 0; pixels[p + 1] = 0; pixels[p + 2] = 0; } //マスク2が白なら色反転 if (mask2Pixels[pp] == 255) { pixels[p] = (byte)(255 - pixels[p]); pixels[p + 1] = (byte)(255 - pixels[p + 1]); pixels[p + 2] = (byte)(255 - pixels[p + 2]); nekocount++; } xCount++; } yCount++; xCount = 0; } return BitmapSource.Create(w, h, source.DpiX, source.DpiY, source.Format, source.Palette, pixels, stride); }
private void CalculateLuminanceBGR565(BitmapSource bitmap) { var width = bitmap.PixelWidth; var height = bitmap.PixelHeight; var stepX = (bitmap.Format.BitsPerPixel + 7) / 8; var bufferSize = width * stepX; var buffer = new byte[bufferSize]; var rect = new Int32Rect(0, 0, width, 1); var luminanceIndex = 0; for (var curY = 0; curY < height; curY++) { bitmap.CopyPixels(rect, buffer, bufferSize, 0); for (var curX = 0; curX < bufferSize; curX += stepX) { var byte1 = buffer[curX]; var byte2 = buffer[curX + 1]; var b5 = byte1 & 0x1F; var g5 = (((byte1 & 0xE0) >> 5) | ((byte2 & 0x03) << 3)) & 0x1F; var r5 = (byte2 >> 2) & 0x1F; var r8 = (r5 * 527 + 23) >> 6; var g8 = (g5 * 527 + 23) >> 6; var b8 = (b5 * 527 + 23) >> 6; // cheap, not fully accurate conversion //var pixel = (byte2 << 8) | byte1; //b8 = (((pixel) & 0x001F) << 3); //g8 = (((pixel) & 0x07E0) >> 2) & 0xFF; //r8 = (((pixel) & 0xF800) >> 8); luminances[luminanceIndex] = (byte)((RChannelWeight * r8 + GChannelWeight * g8 + BChannelWeight * b8) >> ChannelWeight); luminanceIndex++; } rect.Y++; } }
private Texture2D CreateDirectXTexture(BitmapSource source) { var stride = source.Size.Width * 4; using (var buffer = GetPixels(source, stride)) return new Texture2D(device.NativeDevice, CreateTextureDescription(source.Size), new DataRectangle(buffer.DataPointer, stride)); }
public WicBitmapSource(ImagingFactory factory, BitmapSource wicImpl) { this.factory = factory; this.WicImpl = wicImpl; }
private void CalculateLuminanceBGR(BitmapSource bitmap) { var width = bitmap.PixelWidth; var height = bitmap.PixelHeight; var stepX = (bitmap.Format.BitsPerPixel + 7) / 8; var bufferSize = width * stepX; var buffer = new byte[bufferSize]; var rect = new Int32Rect(0, 0, width, 1); var luminanceIndex = 0; for (var curY = 0; curY < height; curY++) { bitmap.CopyPixels(rect, buffer, bufferSize, 0); for (var curX = 0; curX < bufferSize; curX += stepX) { var b = buffer[curX]; var g = buffer[curX + 1]; var r = buffer[curX + 2]; luminances[luminanceIndex] = (byte)((RChannelWeight * r + GChannelWeight * g + BChannelWeight * b) >> ChannelWeight); luminanceIndex++; } rect.Y++; } }
private static Texture2D CreateTexture2DFromBitmapSource(Device device, BitmapSource bitmapSource, TextureLoadOptions options) { // Allocate DataStream to receive the WIC image pixels var stride = bitmapSource.Size.Width * 4; using (var buffer = new DataStream(bitmapSource.Size.Height * stride, true, true)) { // Copy the content of the WIC to the buffer bitmapSource.CopyPixels(stride, buffer); var texture2DDescription = new Texture2DDescription() { Width = bitmapSource.Size.Width, Height = bitmapSource.Size.Height, ArraySize = 1, BindFlags = options.BindFlags, Usage = options.ResourceUsage, CpuAccessFlags = options.CpuAccessFlags, Format = options.Format, MipLevels = options.MipLevels, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), }; bitmapSource.Dispose(); var dataRectangle = new DataRectangle(buffer.DataPointer, stride); return new Texture2D(device, texture2DDescription, dataRectangle); } }
private void UpdateImage(double west, double east, double south, double north, BitmapSource image) { currentImageIndex = (currentImageIndex + 1) % 2; var mapImage = (MapImage)Children[currentImageIndex]; mapImage.Source = null; mapImage.North = double.NaN; // avoid frequent MapRectangle.UpdateData() calls mapImage.West = west; mapImage.East = east; mapImage.South = south; mapImage.North = north; if (image != null) { mapImage.Source = image; AddDownloadEventHandlers(image); } else { BlendImages(); } }
/// <summary> /// Initializes a new instance of the <see cref="XImage"/> class from a WinRT image. /// </summary> XImage(BitmapSource image) { _wrtImage = image; Initialize(); }
public BitmapSource doOperation(BitmapSource image) { return(new FormatConvertedBitmap(image, PixelFormats.Gray8, BitmapPalettes.Gray256, 0.0)); }
/// <summary> /// Gets the image filename. /// </summary> /// <param name="bitmapSource">The bitmap source.</param> internal static string GetImageFilename(BitmapSource bitmapSource) { string filename = bitmapSource.ToString(); filename = UrlDecodeStringFromStringInternal(filename); if (filename.StartsWith("file:///")) filename = filename.Substring(8); // Remove all 3 slashes! else if (filename.StartsWith("file://")) filename = filename.Substring(5); // Keep 2 slashes (UNC path) return filename; }
public static GifBitmapCoder ConvertStciIndexedToGif( StciIndexed aStci, UInt16 aDelay, bool aUseTransparent, int aForeshotingNumber) { var _stciPalette = aStci.Palette; var _colors = new List <Color>(StciIndexed.NUMBER_OF_COLORS); for (int i = 0; i < StciIndexed.NUMBER_OF_COLORS; i++) { _colors.Add(Color.FromRgb(_stciPalette[i * 3], _stciPalette[i * 3 + 1], _stciPalette[i * 3 + 2])); } var _palette = new BitmapPalette(_colors); var _gifCoder = new GifBitmapCoder(_palette); _gifCoder.Extensions.Add(new GifCommentExtension("Egorov A. V. for ja2.su")); Int16 _minOffsetX = Int16.MaxValue; Int16 _minOffsetY = Int16.MaxValue; int foreshotingCount = 0; foreach (var _subImage in aStci.Images) { if (_subImage.AuxData != null && _subImage.AuxData.NumberOfFrames > 0) { foreshotingCount++; } if (aForeshotingNumber > 0 && aForeshotingNumber != foreshotingCount) { continue; } var _header = _subImage.Header; _minOffsetX = Math.Min(_minOffsetX, _header.OffsetX); _minOffsetY = Math.Min(_minOffsetY, _header.OffsetY); } if (_minOffsetX < 0 || _minOffsetY < 0) { var _shiftData = new List <byte>(4); _shiftData.AddRange(BitConverter.GetBytes(_minOffsetX)); _shiftData.AddRange(BitConverter.GetBytes(_minOffsetY)); var _shiftExtension = new GifApplicationExtension(ApplicationId, _shiftData.ToArray()); _gifCoder.Extensions.Add(_shiftExtension); } foreshotingCount = 0; foreach (var _subImage in aStci.Images) { if (_subImage.AuxData != null && _subImage.AuxData.NumberOfFrames > 0) { foreshotingCount++; } if (aForeshotingNumber > 0 && aForeshotingNumber != foreshotingCount) { continue; } var _header = _subImage.Header; var _imageSource = BitmapSource.Create( _header.Width, _header.Height, 96, 96, PixelFormats.Indexed8, _palette, _subImage.ImageData, _header.Width); var _frame = BitmapFrame.Create(_imageSource); var _offsetX = _header.OffsetX; var _offsetY = _header.OffsetY; if (_minOffsetX < 0 || _minOffsetY < 0) { // GIF format suports only positive offsets _offsetX = (short)(_offsetX - _minOffsetX); _offsetY = (short)(_offsetY - _minOffsetY); } var _bf = new GifBitmapFrame(_frame, (ushort)_offsetX, (ushort)_offsetY); if (_subImage.AuxData != null) { var _auxData = new byte[AuxObjectData.SIZE]; _subImage.AuxData.Save(new MemoryStream(_auxData)); _bf.Extensions.Add(new GifApplicationExtension(ApplicationId, _auxData)); } _bf.DisposalMethod = GifFrameDisposalMethod.RestoreToBackgroundColor; _bf.UseGlobalPalette = true; _bf.UseTransparency = aUseTransparent; _bf.Delay = aDelay; if (aUseTransparent) { _bf.TransparentColorIndex = (byte)aStci.Header.TransparentColorIndex; } _gifCoder.AddFrame(_bf); } return(_gifCoder); }
private void ProcessVideo(string fileName) { VideoFileReader reader = new VideoFileReader(); reader.Open(fileName); System.Drawing.Color[] samples = new System.Drawing.Color[_captureRect.Width * _captureRect.Height]; FrameCaptureCollection frameSamples = new FrameCaptureCollection(); bool indeterminate = reader.FrameCount <= 0; if (!indeterminate) { frameSamples.TotalFramesInVideo = (int)reader.FrameCount; frameSamples.DurationNumerator = reader.FrameCount * reader.FrameRate.Denominator; frameSamples.DurationDenominator = reader.FrameRate.Numerator; } //List<byte> allAudio = new List<byte>(); frameSamples.VideoFile = _videoFile; frameSamples.CaptureRect = _captureRect; long frame = 0; DateTime start = DateTime.Now; int preview = 0; Dictionary <long, BitmapSource> thumbnails = new Dictionary <long, BitmapSource>(); do { //List<byte> audio = new List<byte>(); var current = reader.ReadVideoFrame(); if (current == null) { break; } frame++; //allAudio.AddRange(allAudio); for (int i = 0; i < samples.Length; i++) { samples[i] = current.GetPixel(_captureRect.X + i % _captureRect.Width, _captureRect.Y + i / _captureRect.Width); } frameSamples.Add(new FrameCapture(frame, samples)); if (frame % 25 == 0) { preview++; var hBitmap = current.GetHbitmap(); var capture = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(current.Width, current.Height)); capture.Freeze(); if (preview % 10 == 0) { BitmapSource thumbnail = Resize(capture, 200, 130); thumbnails.Add(frame, thumbnail); } DeleteObject(hBitmap); double progressValue; string progressText; if (!indeterminate) { progressValue = (double)frame / reader.FrameCount; progressText = $"{frame} / {reader.FrameCount} ({progressValue:P})"; TimeSpan elapsed = DateTime.Now - start; TimeSpan averagePerFrame = elapsed.Divide(frame); long left = Math.Max(0, reader.FrameCount - frame - 1); TimeSpan timeLeft = averagePerFrame.Multiply(left); progressText += $" ETA {timeLeft:mm\\:ss}"; } else { progressValue = 0.0; progressText = $"{frame} / Unknown"; } Dispatcher.Invoke(() => { if (_isClosing) { return; } Image = capture; txtProgress.Text = progressText; TaskbarItemInfo.ProgressValue = progressValue; proTotal.Value = progressValue; if (indeterminate) { TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Indeterminate; proTotal.IsIndeterminate = true; } }); } current.Dispose(); } while (_running); //byte[] a = allAudio.ToArray(); //Signal s = new Signal(a, 1, a.Length, reader.SampleRate, SampleFormat.Format8BitUnsigned); //for (int index = 0; index < frameSamples.Count; index++) //{ // var frameSample = frameSamples[index]; // frameSample.AudioLevel = s.GetSample(0, (int) frameSample.FrameIndex); //} long framesSampled = frame; long expectedFrames = frameSamples.TotalFramesInVideo; long sampledFrames = frameSamples.Count; if (frameSamples.TotalFramesInVideo == 0) { frameSamples.TotalFramesInVideo = (int)frame; frameSamples.DurationNumerator = frame * reader.FrameRate.Denominator; frameSamples.DurationDenominator = reader.FrameRate.Numerator; } Dispatcher.BeginInvoke(new Action(() => { if (_isClosing) { return; } Thumbnails = thumbnails; Result = frameSamples; DialogResult = true; })); }
protected override void DrawVisualThumbnail(DrawingContext drawingContext, out string title, ref BitmapSource icon) { var aeroColor = (Color)Application.Current.Resources["AeroColor"]; var aeroBrush = new SolidColorBrush(aeroColor); var aeroPen = new Pen(aeroBrush, 7); var grayBrush = new SolidColorBrush(Color.FromArgb(255, 0xaf, 0xaf, 0xaf)); var fileIcon = Icon; var parentLocationIcon = (BitmapSource) Application.Current.Resources["FileClipboardItemParentLocationIcon"]; var fontFamily = (FontFamily)Application.Current.Resources["CuprumFont"]; var typeface = new Typeface(fontFamily, FontStyles.Normal, FontWeights.Light, FontStretches.Normal); const int fileNameTextOffset = VisualThumbnailMargin + 32 + VisualThumbnailMargin / 2; const int parentLocationTextOffset = VisualThumbnailMargin + 16 + VisualThumbnailMargin/2; var fileNameText = new FormattedText(Name, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, 18, aeroBrush); fileNameText.MaxTextWidth = VisualThumbnailWidth - fileNameTextOffset - VisualThumbnailMargin; fileNameText.MaxTextHeight = 32; if (!string.IsNullOrEmpty(ParentLocation)) { var parentLocationText = new FormattedText(ParentLocation, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, 14, grayBrush); parentLocationText.MaxTextWidth = VisualThumbnailWidth - parentLocationTextOffset - VisualThumbnailMargin; parentLocationText.MaxTextHeight = 32; drawingContext.DrawImage(parentLocationIcon, new Rect(VisualThumbnailMargin, VisualThumbnailMargin + 32 + VisualThumbnailMargin, 16, 16)); drawingContext.DrawText(parentLocationText, new Point(parentLocationTextOffset, VisualThumbnailMargin + 32 + VisualThumbnailMargin)); } drawingContext.DrawRectangle(Brushes.White, aeroPen, new Rect(-1, -1, VisualThumbnailWidth + 2, VisualThumbnailHeight + 2)); drawingContext.DrawImage(fileIcon, new Rect(VisualThumbnailMargin, VisualThumbnailMargin, 32, 32)); drawingContext.DrawText(fileNameText, new Point(fileNameTextOffset, VisualThumbnailMargin + fileNameText.MaxTextHeight / 2 - fileNameText.Height / 2)); title = Name; }
/// <summary> /// Add another frame /// </summary> /// <param name="nextFrame">The next frame</param> public void Add(BitmapSource nextFrame) { var jbe = new JpegBitmapEncoder(); jbe.QualityLevel = 100; jbe.Frames.Add(BitmapFrame.Create(nextFrame)); jbe.Save(vs); }
//TODO: factory? protected abstract void DrawVisualThumbnail(DrawingContext drawingContext, out string title, ref BitmapSource icon);
internal BitmapSource CreateIconBitmapSource() { var stride = PixelFormats.Bgr32.BitsPerPixel / 8 * 16; return(BitmapSource.Create(16, 16, 96, 96, PixelFormats.Bgr32, null, new byte[16 * stride], stride)); }
/// <summary> /// Requests pixels from the ChainedCustomBitmapSource. /// </summary> /// <param name="sourceRect"> /// The rectangle of pixels being requested. /// </param> /// <param name="stride"> /// The stride of the destination buffer. /// </param> /// <param name="bufferSize"> /// The size of the destination buffer. /// </param> /// <param name="buffer"> /// The destination buffer. /// </param> /// <remarks> /// The default implementation simply calls CopyPixels on the /// source. /// </remarks> protected override void CopyPixelsCore(Int32Rect sourceRect, int stride, int bufferSize, IntPtr buffer) { BitmapSource source = Source; if (source != null) { // First defer to the base implementation, which will fill in // the buffer from the source and convert the pixel format as // needed. base.CopyPixelsCore(sourceRect, stride, bufferSize, buffer); // Also fetch the color of the upper-left corner (0,0) if the // transparent color has not been specified. Color transparentColor; if (TransparentColor == null) { uint[] firstPixel = new uint[1]; unsafe { fixed(uint *pFirstPixel = firstPixel) { base.CopyPixelsCore(new Int32Rect(0, 0, 1, 1), 4, 4, new IntPtr(pFirstPixel)); Bgra32Pixel *pBgraPixel = (Bgra32Pixel *)pFirstPixel; transparentColor = Color.FromRgb(pBgraPixel->Red, pBgraPixel->Green, pBgraPixel->Blue); } } } else { transparentColor = TransparentColor.Value; } // The buffer has been filled with Bgr32 or Bgra32 pixels. // Now process these pixels and set the alpha channel to 0 for // pixels that match the color key. Leave the other pixels // alone. // // Note: if this buffer pointer came from a managed array, the // array has already been pinned. unsafe { byte *pBytes = (byte *)buffer.ToPointer(); for (int y = 0; y < sourceRect.Height; y++) { Bgra32Pixel *pPixel = (Bgra32Pixel *)pBytes; for (int x = 0; x < sourceRect.Width; x++) { if (pPixel->Red == transparentColor.R && pPixel->Green == transparentColor.G && pPixel->Blue == transparentColor.B) { pPixel->Alpha = 0x00; } pPixel++; } pBytes += stride; } } } }
public void DrawImage(BitmapSource imageSource, Rect rect) { RectangleGeometry geo = new RectangleGeometry(rect); ImageBrush brush = new ImageBrush(); brush.ImageSource = imageSource; brush.Stretch = Stretch.Fill; DrawGeometry(brush, null, geo); }