/// <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); }
public BitmapSource konvoluce(BitmapImage obrazek) { BitmapSource bitmapSource = new FormatConvertedBitmap(obrazek, PixelFormats.Rgb24, null, 0); WriteableBitmap wbmap = new WriteableBitmap(bitmapSource); int sirka = 768; int vyska = 576; int stride = vyska * 4;// možno přehodit sirku za vysku a naopak int size = sirka * stride; byte[] pixely = new byte[size]; byte[] vyslednePixely = new byte[size]; bitmapSource.CopyPixels(pixely, stride, 0); double modra = 0.0; double zelena = 0.0; double cervena = 0.0; int maskaSirka = maska.GetLength(1); int maskaVyska = maska.GetLength(0); int maskaOffset = (maskaSirka - 1) / 2; int vypOffset = 0; int byteOffset = 0; for (int offsetY = maskaOffset; offsetY < vyska - maskaOffset; offsetY++) { for (int offsetX = maskaOffset; offsetX < sirka - maskaOffset; offsetX++) { modra = 0; zelena = 0; cervena = 0; byteOffset = offsetY * stride + offsetX * 4; for (int filterY = -maskaOffset; filterY <= maskaOffset; filterY++) { for (int filterX = -maskaOffset; filterX <= maskaOffset; filterX++) { vypOffset = byteOffset + (filterX * 4) + (filterY * stride);//Umyslná chyba(místo 3 je 4) modra += (double)(pixely[vypOffset]) * maska[filterY + maskaOffset, filterX + maskaOffset]; zelena += (double)(pixely[vypOffset + 1]) * maska[filterY + maskaOffset, filterX + maskaOffset]; cervena += (double)(pixely[vypOffset + 2]) * maska[filterY + maskaOffset, filterX + maskaOffset]; } } modra = faktor * modra + bias; zelena = faktor * zelena + bias; cervena = faktor * cervena + bias; if (modra > 255) { modra = 255; } else if (modra < 0) { modra = 0; } if (zelena > 255) { zelena = 255; } else if (zelena < 0) { zelena = 0; } if (cervena > 255) { cervena = 255; } else if (cervena < 0) { cervena = 0; } vyslednePixely[byteOffset] = (byte)(modra); vyslednePixely[byteOffset + 1] = (byte)(zelena); vyslednePixely[byteOffset + 2] = (byte)(cervena); vyslednePixely[byteOffset + 3] = 255;//Umyslná chyba(není nutný) } } var resultData = BitmapSource.Create(sirka, vyska, 96d, 96d, PixelFormats.Bgr24, null, vyslednePixely, stride); return(resultData); }
//Detekce rohu public BitmapSource detekce(BitmapSource obrazek, int threshold) { int t2 = threshold; int seda; byte[] barva = { 0, 0, 0, 0 }; BitmapSource bitmapSource = new FormatConvertedBitmap(obrazek, PixelFormats.Rgb24, null, 0); WriteableBitmap wbmap = new WriteableBitmap(bitmapSource); int vyska = wbmap.PixelHeight; int sirka = wbmap.PixelWidth; int stride = wbmap.PixelWidth * 4; int size = wbmap.PixelHeight * stride; byte[] pixely = new byte[size]; wbmap.CopyPixels(pixely, stride, 0); //Převod na šedotonovy obraz for (int y = 0; y < wbmap.PixelHeight; y++) { for (int x = 0; x < wbmap.PixelWidth; x++) { int index = y * stride + 4 * x; byte red = pixely[index]; byte green = pixely[index + 1]; byte blue = pixely[index + 2]; // byte alpha = pixely[index + 3]; seda = (red + green + blue) / 3; pixely[index] = (byte)seda; barva[0] = (byte)seda; barva[1] = (byte)seda; barva[2] = (byte)seda; wbmap.WritePixels(new Int32Rect(x, y, 1, 1), barva, stride, 0); } } List <Souradnice> seznamRohu = new List <Souradnice>(); //Obrazek1.Source = wbmap; WriteableBitmap cdmap = new WriteableBitmap(wbmap); //Trajkovic-uv detektor rohu int[,] corner = new int[cdmap.PixelWidth, cdmap.PixelHeight]; int ra, rb, iAa, iA, iC, iB, iBb; int[,] m = new int[cdmap.PixelWidth, cdmap.PixelHeight]; int b1, b2, b, a, c; for (int y = 1; y < cdmap.PixelHeight - 1; y++) // simple cornerness measure, minimal variatons among directions { for (int x = 1; x < cdmap.PixelWidth - 1; x++) { int index = y * stride + 4 * x; iC = pixely[index]; //ve skutecnosti odkazuje na cervenou barvu index = y * stride + 4 * (x + 1); iA = pixely[index]; index = y * stride + 4 * (x - 1); iAa = pixely[index]; index = (y + 1) * stride + 4 * x; iB = pixely[index]; index = (y - 1) * stride + 4 * x; iBb = pixely[index]; ra = (iA - iC) * (iA - iC) + (iAa - iC) * (iAa - iC); rb = (iB - iC) * (iB - iC) + (iBb - iC) * (iBb - iC); c = ra; b1 = (iB - iA) * (iA - iC) + (iBb - iAa) * (iAa - iC); b2 = (iB - iAa) * (iAa - iC) + (iBb - iA) * (iA - iC); b = Math.Min(b1, b2); a = rb - ra - 2 * b; if ((b < 0) & ((a + b) > 0)) { m[x, y] = c - ((b * b) / a); } else { m[x, y] = Math.Min(ra, rb); } } } for (int y = 1; y < cdmap.PixelHeight - 1; y++) { for (int x = 1; x < cdmap.PixelWidth - 1; x++) { if (m[x, y] > t2) { cdmap.WritePixels(new Int32Rect(x, y, 1, 1), oznaceniB, stride, 0); seznamRohu.Add(new Souradnice { coordX = x, coordY = y }); wbmap.WritePixels(new Int32Rect(x, y, 1, 1), oznaceniR, stride, 0); } else { cdmap.WritePixels(new Int32Rect(x, y, 1, 1), oznaceniC, stride, 0); } } } return(wbmap); }
private void LoadImage(MemoryStream stream, ImageFormat format) { mipMaps = new List <MipMap>(); switch (format) { case ImageFormat.DDS: { LoadImageDDS(stream, format); break; } case ImageFormat.TGA: { LoadImageTGA(stream, format); break; } case ImageFormat.BMP: { LoadImageBMP(stream, format); break; } case ImageFormat.PNG: case ImageFormat.JPEG: { BitmapSource frame = null; if (format == ImageFormat.PNG) { frame = new PngBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default).Frames[0]; } else if (format == ImageFormat.JPEG) { frame = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default).Frames[0]; } if (!checkPowerOfTwo(frame.PixelWidth) || !checkPowerOfTwo(frame.PixelHeight)) { throw new Exception("dimensions not power of two"); } FormatConvertedBitmap srcBitmap = new FormatConvertedBitmap(); srcBitmap.BeginInit(); srcBitmap.Source = frame; srcBitmap.DestinationFormat = PixelFormats.Bgra32; srcBitmap.EndInit(); byte[] pixels = new byte[srcBitmap.PixelWidth * srcBitmap.PixelHeight * 4]; frame.CopyPixels(pixels, srcBitmap.PixelWidth * 4, 0); pixelFormat = PixelFormat.ARGB; MipMap mipmap = new MipMap(pixels, srcBitmap.PixelWidth, srcBitmap.PixelHeight, PixelFormat.ARGB); mipMaps.Add(mipmap); break; } default: throw new Exception(); } }
private void Window_Loaded(object sender, RoutedEventArgs e) { try { //System.Drawing.Image img = System.Drawing.Image.FromFile( m_images.m_pathView ); if (!File.Exists(m_images.m_pathView)) { VOP.Controls.MessageBoxEx.Show( VOP.Controls.MessageBoxExStyle.Simple, this, (string)this.FindResource("ResStr_Image_file_not_found"), (string)this.FindResource("ResStr_Error") ); this.Close(); } BitmapImage bi3 = new BitmapImage(); bi3.BeginInit(); bi3.UriSource = new Uri(m_images.m_pathView, UriKind.RelativeOrAbsolute); // Fixed bms bug #0059616: Set the DecodePixelWidth to avoid rotation operation cached memory. // Comment from MSDN: // To save significant application memory, set the DecodePixelWidth or // DecodePixelHeight of the BitmapImage value of the image source to the desired // height or width of the rendered image. If you don't do this, the application will // cache the image as though it were rendered as its normal size rather then just // the size that is displayed. // Note: In order to preserve aspect ratio, set DecodePixelWidth // or DecodePixelHeight but not both. //bi3.DecodePixelWidth = img.Width; //m_actualWidth = img.Width; bi3.EndInit(); m_actualWidth = bi3.PixelWidth; // Begin: Fix 61368 if (m_images.m_colorMode == EnumColorType.black_white) { BitmapSource bmpSrc = bi3; bmpSrc = BitmapFrame.Create(new TransformedBitmap(bmpSrc, new ScaleTransform(0.4, 0.4))); // https://msdn.microsoft.com/en-us/library/system.windows.media.imaging.formatconvertedbitmap(v=vs.100).aspx FormatConvertedBitmap convertedBitmap = new FormatConvertedBitmap(); convertedBitmap.BeginInit(); convertedBitmap.Source = bmpSrc; convertedBitmap.DestinationFormat = PixelFormats.Gray2; convertedBitmap.EndInit(); previewImg.Source = convertedBitmap; } else { previewImg.Source = bi3; } // End: Fix 61368 FitTheWindow(); CenterImage(); } catch (Exception) { } InitFontSize(); }
private void OnCompositionTargetRendering(object sender, EventArgs e) { if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this)) { return; } int xres = NdiWidth; int yres = NdiHeight; int frNum = NdiFrameRateNumerator; int frDen = NdiFrameRateDenominator; RenderTargetBitmap targetBitmap = null; FormatConvertedBitmap fmtConvertedBmp = null; // sanity if (sendInstancePtr == IntPtr.Zero || xres < 8 || yres < 8) { return; } if (targetBitmap == null || targetBitmap.PixelWidth != xres || targetBitmap.PixelHeight != yres) { // Create a properly sized RenderTargetBitmap targetBitmap = new RenderTargetBitmap(xres, yres, 96, 96, PixelFormats.Pbgra32); fmtConvertedBmp = new FormatConvertedBitmap(); fmtConvertedBmp.BeginInit(); fmtConvertedBmp.Source = targetBitmap; fmtConvertedBmp.DestinationFormat = PixelFormats.Bgra32; fmtConvertedBmp.EndInit(); } // clear to prevent trails targetBitmap.Clear(); // render the content into the bitmap targetBitmap.Render(this.Child); int stride = (xres * 32 /*BGRA bpp*/ + 7) / 8; int bufferSize = yres * stride; float aspectRatio = (float)xres / (float)yres; // allocate some memory for a video buffer IntPtr bufferPtr = Marshal.AllocHGlobal(bufferSize); // We are going to create a progressive frame at 60Hz. NDIlib.video_frame_v2_t videoFrame = new NDIlib.video_frame_v2_t() { // Resolution xres = NdiWidth, yres = NdiHeight, // Use BGRA video FourCC = NDIlib.FourCC_type_e.FourCC_type_BGRA, // The frame-eate frame_rate_N = frNum, frame_rate_D = frDen, // The aspect ratio picture_aspect_ratio = aspectRatio, // This is a progressive frame frame_format_type = NDIlib.frame_format_type_e.frame_format_type_progressive, // Timecode. timecode = NDIlib.send_timecode_synthesize, // The video memory used for this frame p_data = bufferPtr, // The line to line stride of this image line_stride_in_bytes = stride, // no metadata p_metadata = IntPtr.Zero, // only valid on received frames timestamp = 0 }; if (UnPremultiply && fmtConvertedBmp != null) { fmtConvertedBmp.CopyPixels(new Int32Rect(0, 0, xres, yres), bufferPtr, bufferSize, stride); } else { // copy the pixels into the buffer targetBitmap.CopyPixels(new Int32Rect(0, 0, xres, yres), bufferPtr, bufferSize, stride); } // add it to the output queue AddVideoFrame(videoFrame); }
/// <summary> /// Handles the Tick event of the timer control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void timer_Tick(object sender, EventArgs e) { // Lock on OpenGL. lock (gl) { // Start the stopwatch so that we can time the rendering. stopwatch.Restart(); // Make GL current. gl.MakeCurrent(); // If there is a draw handler, then call it. var handler = OpenGLDraw; if (handler != null) { handler(this, eventArgsFast); } else { gl.Clear(OpenGL.GL_COLOR_BUFFER_BIT); } // Draw the FPS. if (DrawFPS) { gl.DrawText(5, 5, 1.0f, 0.0f, 0.0f, "Courier New", 12.0f, string.Format("Draw Time: {0:0.0000} ms ~ {1:0.0} FPS", frameTime, 1000.0 / frameTime)); gl.Flush(); } // Render. gl.Blit(IntPtr.Zero); switch (RenderContextType) { case RenderContextType.DIBSection: { RenderContextProviders.DIBSectionRenderContextProvider provider = gl.RenderContextProvider as RenderContextProviders.DIBSectionRenderContextProvider; // TODO: We have to remove the alpha channel - for some reason it comes out as 0.0 // meaning the drawing comes out transparent. FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap(); newFormatedBitmapSource.BeginInit(); newFormatedBitmapSource.Source = BitmapConversion.HBitmapToBitmapSource(provider.DIBSection.HBitmap); newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24; newFormatedBitmapSource.EndInit(); // Copy the pixels over. image.Source = newFormatedBitmapSource; } break; case RenderContextType.NativeWindow: break; case RenderContextType.HiddenWindow: break; case RenderContextType.FBO: { RenderContextProviders.FBORenderContextProvider provider = gl.RenderContextProvider as RenderContextProviders.FBORenderContextProvider; // TODO: We have to remove the alpha channel - for some reason it comes out as 0.0 // meaning the drawing comes out transparent. FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap(); newFormatedBitmapSource.BeginInit(); newFormatedBitmapSource.Source = BitmapConversion.HBitmapToBitmapSource(provider.InternalDIBSection.HBitmap); newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24; newFormatedBitmapSource.EndInit(); // Copy the pixels over. image.Source = newFormatedBitmapSource; } break; case RenderContextType.PBO: { PBORenderContextProvider provider = gl.RenderContextProvider as PBORenderContextProvider; var width = provider.Width; var height = provider.Height; var pixelsPtr = provider.PixelPtr; var size = provider.Size; var stride = provider.Stride; writeableBitmap.WritePixels(new Int32Rect(0, 0, width, height), pixelsPtr, size, stride, 0, 0); image.Source = writeableBitmap; } break; default: break; } // Stop the stopwatch. stopwatch.Stop(); // Store the frame time. frameTime = stopwatch.Elapsed.TotalMilliseconds; } }
private void MyTimer_Tick(object sender, EventArgs e) { //キー入力取得用 //Keyを仮想キーコードに変換 int vKey1 = KeyInterop.VirtualKeyFromKey(Key.RightCtrl); int vKey2 = KeyInterop.VirtualKeyFromKey(Key.RightShift); //キーの状態を取得 short key1state = GetAsyncKeyState(vKey1); short key2state = GetAsyncKeyState(vKey2); //右Ctrlキー+右Shiftキーが押されていたら if ((key1state & 0x8000) >> 15 == 1 & ((key2state & 1) == 1)) { //一番手前のウィンドウ IntPtr hWindowForeground = GetForegroundWindow(); //ハンドル取得 RECT rectWindowForeground; GetWindowRect(hWindowForeground, out rectWindowForeground); //Rect取得 MyTextBlock1.Text = $"{rectWindowForeground} 一番手前(アクティブ)ウィンドウRect"; //画面全体の画像からウィンドウRect範囲を切り出す if (rbScreen.IsChecked == true) { var screenDC = GetDC(IntPtr.Zero); //画面全体のDC、コピー元 var memDC = CreateCompatibleDC(screenDC); //コピー先DC作成 int width = rectWindowForeground.right - rectWindowForeground.left; int height = rectWindowForeground.bottom - rectWindowForeground.top; var hBmp = CreateCompatibleBitmap(screenDC, width, height); //コピー先のbitmapオブジェクト作成 SelectObject(memDC, hBmp); //コピー先DCにbitmapオブジェクトを指定 //ビットブロック転送、コピー元からコピー先へ BitBlt(memDC, 0, 0, width, height, screenDC, rectWindowForeground.left, rectWindowForeground.top, SRCCOPY); //bitmapオブジェクトからbitmapSource作成 BitmapSource source = Imaging.CreateBitmapSourceFromHBitmap(hBmp, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); //後片付け DeleteObject(hBmp); ReleaseDC(IntPtr.Zero, screenDC); ReleaseDC(IntPtr.Zero, memDC); //画像表示 MyImage.Source = source; } //ウィンドウDCからコピー else if (rbWindow.IsChecked == true) { var screenDC = GetDC(hWindowForeground);//ウィンドウのDC var memDC = CreateCompatibleDC(screenDC); int width = rectWindowForeground.right - rectWindowForeground.left; int height = rectWindowForeground.bottom - rectWindowForeground.top; var hBmp = CreateCompatibleBitmap(screenDC, width, height); SelectObject(memDC, hBmp); BitBlt(memDC, 0, 0, width, height, screenDC, 0, 0, SRCCOPY); var source = Imaging.CreateBitmapSourceFromHBitmap(hBmp, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); DeleteObject(hBmp); ReleaseDC(IntPtr.Zero, screenDC); ReleaseDC(IntPtr.Zero, memDC); MyImage.Source = source; } //ウィンドウDCからコピーしてアルファ値を255にする else if (rbWindowAlpah255.IsChecked == true) { var screenDC = GetDC(hWindowForeground);//ウィンドウのDC var memDC = CreateCompatibleDC(screenDC); int width = rectWindowForeground.right - rectWindowForeground.left; int height = rectWindowForeground.bottom - rectWindowForeground.top; var hBmp = CreateCompatibleBitmap(screenDC, width, height); SelectObject(memDC, hBmp); BitBlt(memDC, 0, 0, width, height, screenDC, 0, 0, SRCCOPY); var source = Imaging.CreateBitmapSourceFromHBitmap(hBmp, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); DeleteObject(hBmp); ReleaseDC(IntPtr.Zero, screenDC); ReleaseDC(IntPtr.Zero, memDC); //ピクセルフォーマットをBgr24に変換することでアルファ値を255に見立てている source = new FormatConvertedBitmap(source, PixelFormats.Bgr24, source.Palette, 0); MyImage.Source = source; } } }
private void OnSaveImpl( Document input, Stream output, SaveConfigToken token, Surface scratchSurface, ProgressEventHandler callback) { HDPhotoSaveConfigToken hdToken = token as HDPhotoSaveConfigToken; WmpBitmapEncoder wbe = new WmpBitmapEncoder(); using (RenderArgs ra = new RenderArgs(scratchSurface)) { input.Render(ra, true); } MemoryBlock block = scratchSurface.Scan0; IntPtr scan0 = block.Pointer; double dpiX; double dpiY; switch (input.DpuUnit) { case MeasurementUnit.Centimeter: dpiX = Document.DotsPerCmToDotsPerInch(input.DpuX); dpiY = Document.DotsPerCmToDotsPerInch(input.DpuY); break; case MeasurementUnit.Inch: dpiX = input.DpuX; dpiY = input.DpuY; break; case MeasurementUnit.Pixel: dpiX = Document.GetDefaultDpu(MeasurementUnit.Inch); dpiY = Document.GetDefaultDpu(MeasurementUnit.Inch); break; default: throw new InvalidEnumArgumentException(); } BitmapSource bitmapSource = BitmapFrame.Create( scratchSurface.Width, scratchSurface.Height, dpiX, dpiY, System.Windows.Media.PixelFormats.Bgra32, null, scan0, (int)block.Length, // TODO: does not support >2GB images scratchSurface.Stride); FormatConvertedBitmap fcBitmap = new FormatConvertedBitmap( bitmapSource, hdToken.BitDepth == 24 ? PixelFormats.Bgr24 : PixelFormats.Bgra32, null, 0); BitmapFrame outputFrame0 = BitmapFrame.Create(fcBitmap); wbe.Frames.Add(outputFrame0); wbe.ImageQualityLevel = (float)hdToken.Quality / 100.0f; string tempFileName = FileSystem.GetTempFileName(); FileStream tempFileOut = new FileStream(tempFileName, FileMode.Create, FileAccess.Write, FileShare.Read); wbe.Save(tempFileOut); tempFileOut.Close(); tempFileOut = null; FileStream tempFileIn = new FileStream(tempFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read); WmpBitmapDecoder wbd = new WmpBitmapDecoder(tempFileIn, BitmapCreateOptions.None, BitmapCacheOption.None); BitmapFrame ioFrame0 = wbd.Frames[0]; InPlaceBitmapMetadataWriter metadata2 = ioFrame0.CreateInPlaceBitmapMetadataWriter(); CopyMetadataTo(metadata2, input.Metadata); tempFileIn.Close(); tempFileIn = null; FileStream tempFileIn2 = new FileStream(tempFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read); Utility.CopyStream(tempFileIn2, output); tempFileIn2.Close(); tempFileIn2 = null; try { File.Delete(tempFileName); } catch (Exception) { } // WPF doesn't give us an IDisposable implementation on its types Utility.GCFullCollect(); }
/// <summary> /// Search archive <paramref name="arc"/> for baseline image. /// </summary> internal void ReadBaseline(BellArchive arc, Entry entry) { var header = ReadHeader(); if (!((header[0] & 1) == 1 && 'd' == this.Type || header[0] == 1 && 'a' == this.Type)) { return; } var scheme = arc.Scheme; var dir = (List <Entry>)arc.Dir; int i = dir.IndexOf(entry); while (--i >= 0 && "image" == dir[i].Type) { using (var input = arc.OpenEntry(dir[i])) { int type = input.ReadByte(); if ('d' == type) { continue; } if ('a' == type) { int id = input.ReadByte(); if (id != scheme.Value2) { break; } using (var bin = new BinaryStream(input, dir[i].Name)) using (var base_image = new AImageReader(bin, scheme)) { var base_header = base_image.ReadHeader(); if (1 == base_header[0]) { continue; } // check if image width/height are the same if (base_header[3] == header[3] && base_header[4] == header[4]) { base_image.Unpack(); Baseline = base_image.Data; } } } else if ('b' == type || 'c' == type) { var size_buf = new byte[4]; input.Read(size_buf, 0, 4); int png_size = BigEndian.ToInt32(size_buf, 0); BitmapSource frame; // work-around for possible extra padding before PNG data using (var membuf = new MemoryStream(png_size + 4)) { input.CopyTo(membuf); membuf.Seek(-png_size, SeekOrigin.End); var decoder = new PngBitmapDecoder(membuf, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); frame = decoder.Frames[0]; } Info.Width = (uint)frame.PixelWidth; Info.Height = (uint)frame.PixelHeight; if (frame.Format.BitsPerPixel != 32) { frame = new FormatConvertedBitmap(frame, PixelFormats.Bgra32, null, 0); } int stride = frame.PixelWidth * 4; var pixels = new byte[stride * frame.PixelHeight]; frame.CopyPixels(pixels, stride, 0); Baseline = pixels; } break; } } }
public PixelFormatsExample() { //<SnippetPixelFormatConversion> ///// Create a BitmapImage and set it's DecodePixelWidth to 200. Use ///// ///// this BitmapImage as a source for other BitmapSource objects. ///// BitmapImage myBitmapImage = new BitmapImage(); // BitmapSource objects like BitmapImage can only have their properties // changed within a BeginInit/EndInit block. myBitmapImage.BeginInit(); myBitmapImage.UriSource = new Uri("sampleImages/WaterLilies.jpg", UriKind.Relative); // To save significant application memory, set the DecodePixelWidth or // DecodePixelHeight of the BitmapImage value of the image source to the desired // height or width of the rendered image. If you don't do this, the application will // cache the image as though it were rendered as its normal size rather then just // the size that is displayed. // Note: In order to preserve aspect ratio, set DecodePixelWidth // or DecodePixelHeight but not both. myBitmapImage.DecodePixelWidth = 200; myBitmapImage.EndInit(); ////////// Convert the BitmapSource to a new format //////////// // Use the BitmapImage created above as the source for a new BitmapSource object // which is set to a gray scale format using the FormatConvertedBitmap BitmapSource. // Note: New BitmapSource does not cache. It is always pulled when required. FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap(); // BitmapSource objects like FormatConvertedBitmap can only have their properties // changed within a BeginInit/EndInit block. newFormatedBitmapSource.BeginInit(); // Use the BitmapSource object defined above as the source for this new // BitmapSource (chain the BitmapSource objects together). newFormatedBitmapSource.Source = myBitmapImage; // Set the new format to Gray32Float (grayscale). newFormatedBitmapSource.DestinationFormat = createPixelFormat(); newFormatedBitmapSource.EndInit(); //</SnippetPixelFormatConversion> // Create Image Element Image myImage = new Image(); myImage.Width = 200; //set image source myImage.Source = newFormatedBitmapSource; // Add Image to the UI StackPanel myStackPanel = new StackPanel(); myStackPanel.Children.Add(myImage); // Add TextBox // TextBlock myTextBlock = new TextBlock(); // myTextBlock.Text = "Mask Value: " + stringOfValues + " bpp: " + bpp.ToString(); // myStackPanel.Children.Add(myTextBlock); this.Content = myStackPanel; }
public Gray8Image ToGray8Image() { var bitmap = new FormatConvertedBitmap(ToBitmapSource(), PixelFormats.Gray8, null, 0); return(new Gray8Image(bitmap)); }
void BlendLayer(WriteableBitmap canvas, ImageData layer) { BitmapSource source = layer.Bitmap; if (source.Format.BitsPerPixel != 32) { source = new FormatConvertedBitmap(source, PixelFormats.Bgra32, null, 0); } // determine coordinates of the intersection of layer and canvas var src_rect = new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight); if (layer.OffsetX < 0) { src_rect.X = -layer.OffsetX; src_rect.Width += layer.OffsetX; } if (layer.OffsetY < 0) { src_rect.Y = -layer.OffsetY; src_rect.Height += layer.OffsetY; } if (!src_rect.HasArea) { return; } var layer_rect = new Rectangle(layer.OffsetX, layer.OffsetY, source.PixelWidth, source.PixelHeight); var canvas_rect = new Rectangle(0, 0, canvas.PixelWidth, canvas.PixelHeight); layer_rect.Intersect(canvas_rect); if (layer_rect.Width <= 0 || layer_rect.Height <= 0) { return; } // copy out layer area int src_stride = src_rect.Width * 4; var pixels = new byte[src_stride * src_rect.Height]; source.CopyPixels(src_rect, pixels, src_stride, 0); // perform blending within established coordinates int pixel_size = (canvas.Format.BitsPerPixel + 7) / 8; int canvas_stride = canvas.BackBufferStride; int dst_row = layer_rect.Y * canvas_stride + layer_rect.X * pixel_size; canvas.Lock(); unsafe { byte *buffer = (byte *)canvas.BackBuffer; for (int src = 0; src < pixels.Length; src += src_stride) { byte *dst = buffer + dst_row; for (int x = 0; x < src_stride; x += 4) { byte src_alpha = pixels[src + x + 3]; if (0xFF == src_alpha) { for (int i = 0; i < pixel_size; ++i) { dst[i] = pixels[src + x + i]; } } else if (src_alpha > 0) { dst[0] = (byte)((pixels[src + x + 0] * src_alpha + dst[0] * (0xFF - src_alpha)) / 0xFF); dst[1] = (byte)((pixels[src + x + 1] * src_alpha + dst[1] * (0xFF - src_alpha)) / 0xFF); dst[2] = (byte)((pixels[src + x + 2] * src_alpha + dst[2] * (0xFF - src_alpha)) / 0xFF); if (pixel_size > 3) { dst[3] = (byte)Math.Max(src_alpha, dst[3]); } } dst += pixel_size; } dst_row += canvas_stride; } } canvas.Unlock(); }
//表示中の画像の色を取得、パレットにコピー private void GetUsedColor(BitmapSource source) { var cb = new FormatConvertedBitmap(source, PixelFormats.Rgb24, source.Palette, 0); var wb = new WriteableBitmap(cb); int h = wb.PixelHeight; int w = wb.PixelWidth; int stride = wb.BackBufferStride;// (w * wb.Format.BitsPerPixel + 7) / 8; byte[] pixels = new byte[h * stride]; wb.CopyPixels(pixels, stride, 0); long p = 0; int[] colors = new int[256 * 256 * 256];//1700万色 int numColor; //RGBをintに変換してint配列に入れる for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { p = y * stride + (x * 3); var r = pixels[p]; var g = pixels[p + 1]; var b = pixels[p + 2]; numColor = pixels[p] + pixels[p + 1] * 256 + pixels[p + 2] * 256 * 256; colors[numColor]++; var nekoR = numColor % 256; var nekoG = numColor / 256 % 256; var nekoB = numColor / 256 / 256; } } //数値が入っているindexだけをlistに追加 List <int> listColor = new List <int>(256 * 256 * 256); for (int i = 0; i < colors.Length; ++i) { if (colors[i] != 0) { listColor.Add(i); } } //MessageBox.Show(listColor.Count.ToString()); //パレット初期化 PalettePanColorDel(); MyPalette.Clear(); NumericScrollBar.Value = listColor.Count; TextBlockUsedColorCount.Text = "使用色数:" + listColor.Count.ToString(); //listの値からRGBに戻してパレットに追加表示 Color myColor; int iColor, rr, gg, bb; for (int i = 0; i < listColor.Count && i < MyBorderPalette.Length; ++i) { iColor = listColor[i]; rr = iColor % 256; gg = iColor / 256 % 256; bb = iColor / 256 / 256; myColor = Color.FromRgb((byte)rr, (byte)gg, (byte)bb); MyBorderPalette[i].Background = new SolidColorBrush(myColor); MyPalette.Add(myColor); } }
private static void SetGrayImage(Image element, FormatConvertedBitmap value) { element.SetValue(GrayImageProperty, value); }
//--------------------------------------------------------------------------- /** * @fn public void OpenImage(string strPath) * @brief Align Control에 string path로 이미지 Open. * @return * @param * @remark * - * @author 선경규(Kyeong Kyu - Seon) * @date 2020/3/9 16:39 */ public void OpenImage(string strPath) { Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate() { try { if (!File.Exists(strPath)) { m_ImgBrs = null; m_ImgBrsOrg = null; lib_Canvas.Background = Brushes.Transparent; return; } FileInfo fi = new FileInfo(strPath); m_strPath = strPath; m_strFileName = strPath.Substring(strPath.LastIndexOf('\\') + 1); m_strExtension = fi.Extension; m_strCreationTime = fi.CreationTime.ToString("yyyy.MM.dd HH:mm:ss"); BitmapImage bmpImg = new BitmapImage(); FileStream source = File.OpenRead(strPath); //bmpImg.Format = PixelFormats.Bgr32; bmpImg.BeginInit(); bmpImg.CacheOption = BitmapCacheOption.OnLoad; bmpImg.StreamSource = source; bmpImg.EndInit(); WriteableBitmap wbm = null; FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap(); // BitmapSource objects like FormatConvertedBitmap can only have their properties // changed within a BeginInit/EndInit block. newFormatedBitmapSource.BeginInit(); // Use the BitmapSource object defined above as the source for this new // BitmapSource (chain the BitmapSource objects together). newFormatedBitmapSource.Source = bmpImg; // Set the new format to Gray32Float (grayscale). newFormatedBitmapSource.DestinationFormat = PixelFormats.Bgr24; newFormatedBitmapSource.EndInit(); wbm = new WriteableBitmap(newFormatedBitmapSource); m_ImgBrs = new ImageBrush(wbm); m_ImgBrs.Stretch = Stretch.None; lib_Canvas.Width = m_ImgBrs.ImageSource.Width; lib_Canvas.Height = m_ImgBrs.ImageSource.Height; lib_Canvas.Background = m_ImgBrs; m_nWidth = wbm.PixelWidth; m_nHeight = wbm.PixelHeight; m_nChannel = (int)(wbm.Format.BitsPerPixel / 8.0); m_nStride = (m_nWidth * m_nChannel + 3) & ~3; m_dDpiX = wbm.DpiX; m_dDpiY = wbm.DpiY; m_ImgBrsOrg = m_ImgBrs.Clone(); m_dScale = myScaleTransform.ScaleX; } catch (Exception) { } })); }
public ChainedBitmapSourcesExample() { ///// Create a BitmapImage and set it's DecodePixelWidth to 200. Use ///// ///// this BitmapImage as a source for other BitmapSource objects. ///// BitmapImage myBitmapImage = new BitmapImage(); // BitmapSource objects like BitmapImage can only have their properties // changed within a BeginInit/EndInit block. myBitmapImage.BeginInit(); myBitmapImage.UriSource = new Uri("sampleImages/WaterLilies.jpg", UriKind.Relative); // To save significant application memory, set the DecodePixelWidth or // DecodePixelHeight of the BitmapImage value of the image source to the desired // height or width of the rendered image. If you don't do this, the application will // cache the image as though it were rendered as its normal size rather then just // the size that is displayed. // Note: In order to preserve aspect ratio, set DecodePixelWidth // or DecodePixelHeight but not both. myBitmapImage.DecodePixelWidth = 200; myBitmapImage.EndInit(); /////////////////// Create a BitmapSource that Rotates the image ////////////////////// // Use the BitmapImage created above as the source for a new BitmapSource object // that will be scaled to a different size. Create a new BitmapSource by // scaling the original one. // Note: New BitmapSource does not cache. It is always pulled when required. // Create the new BitmapSource that will be used to scale the size of the source. TransformedBitmap myRotatedBitmapSource = new TransformedBitmap(); // BitmapSource objects like TransformedBitmap can only have their properties // changed within a BeginInit/EndInit block. myRotatedBitmapSource.BeginInit(); // Use the BitmapSource object defined above as the source for this BitmapSource. // This creates a "chain" of BitmapSource objects which essentially inherit from each other. myRotatedBitmapSource.Source = myBitmapImage; // Multiply the size of the X and Y axis of the source by 3. myRotatedBitmapSource.Transform = new RotateTransform(90); myRotatedBitmapSource.EndInit(); // Create a new BitmapSource using a different format than the original one. FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap(); // BitmapSource objects like FormatConvertedBitmap can only have their properties // changed within a BeginInit/EndInit block. newFormatedBitmapSource.BeginInit(); newFormatedBitmapSource.Source = myRotatedBitmapSource; newFormatedBitmapSource.DestinationFormat = PixelFormats.Gray32Float; newFormatedBitmapSource.EndInit(); // Create Image Element Image myImage = new Image(); myImage.Width = 200; //set image source myImage.Source = newFormatedBitmapSource; // Add Image to the UI StackPanel myStackPanel = new StackPanel(); myStackPanel.Children.Add(myImage); this.Content = myStackPanel; }
private void test2(BitmapSource source) { BitmapPalette palette = new BitmapPalette(source, 16); var cb = new FormatConvertedBitmap(source, PixelFormats.Indexed8, null, 0); }
public FormatConvertedBitmapExample2() { ///// Create a BitmapImage and set it's DecodePixelWidth to 200. Use ///// ///// this BitmapImage as a source for other BitmapSource objects. ///// BitmapImage myBitmapImage = new BitmapImage(); // BitmapSource objects like BitmapImage can only have their properties // changed within a BeginInit/EndInit block. myBitmapImage.BeginInit(); myBitmapImage.UriSource = new Uri(@"sampleImages/WaterLilies.jpg", UriKind.Relative); // To save significant application memory, set the DecodePixelWidth or // DecodePixelHeight of the BitmapImage value of the image source to the desired // height or width of the rendered image. If you don't do this, the application will // cache the image as though it were rendered as its normal size rather then just // the size that is displayed. // Note: In order to preserve aspect ratio, set DecodePixelWidth // or DecodePixelHeight but not both. myBitmapImage.DecodePixelWidth = 200; myBitmapImage.EndInit(); ////////// Convert the BitmapSource to a new format //////////// // Use the BitmapImage created above as the source for a new BitmapSource object // which is set to a two color pixel format using the FormatConvertedBitmap BitmapSource. // Note: New BitmapSource does not cache. It is always pulled when required. FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap(); // BitmapSource objects like FormatConvertedBitmap can only have their properties // changed within a BeginInit/EndInit block. newFormatedBitmapSource.BeginInit(); // Use the BitmapSource object defined above as the source for this new // BitmapSource (chain the BitmapSource objects together). newFormatedBitmapSource.Source = myBitmapImage; // Because the DestinationFormat for the FormatConvertedBitmap will be an // indexed pixel format (Indexed1),a DestinationPalette also needs to be specified. // Below, create a custom two color palette to be used for the DestinationPalette. List <System.Windows.Media.Color> colors = new List <System.Windows.Media.Color>(); colors.Add(System.Windows.Media.Colors.Red); colors.Add(System.Windows.Media.Colors.Blue); BitmapPalette myPalette = new BitmapPalette(colors); // Set the DestinationPalette property to the custom palette created above. newFormatedBitmapSource.DestinationPalette = myPalette; // Set the DestinationFormat to the palletized pixel format of Indexed1. newFormatedBitmapSource.DestinationFormat = PixelFormats.Indexed1; newFormatedBitmapSource.EndInit(); // Create Image Element Image myImage = new Image(); myImage.Width = 200; //set image source myImage.Source = newFormatedBitmapSource; // Add Image to the UI StackPanel myStackPanel = new StackPanel(); myStackPanel.Children.Add(myImage); this.Content = myStackPanel; }
public SuccessStoryAchievementsList(List <Achievements> ListAchievements, dynamic Win = null) { InitializeComponent(); this.Win = Win; List <listAchievements> ListBoxAchievements = new List <listAchievements>(); for (int i = 0; i < ListAchievements.Count; i++) { DateTime? dateUnlock; BitmapImage iconImage = new BitmapImage(); FormatConvertedBitmap ConvertBitmapSource = new FormatConvertedBitmap(); bool isGray = false; iconImage.BeginInit(); if (ListAchievements[i].DateUnlocked == default(DateTime) || ListAchievements[i].DateUnlocked == null) { dateUnlock = null; if (ListAchievements[i].UrlLocked == "") { iconImage.UriSource = new Uri(ListAchievements[i].UrlUnlocked, UriKind.RelativeOrAbsolute); isGray = true; } else { iconImage.UriSource = new Uri(ListAchievements[i].UrlLocked, UriKind.RelativeOrAbsolute); } } else { iconImage.UriSource = new Uri(ListAchievements[i].UrlUnlocked, UriKind.RelativeOrAbsolute); dateUnlock = ListAchievements[i].DateUnlocked; } iconImage.EndInit(); ConvertBitmapSource.BeginInit(); ConvertBitmapSource.Source = iconImage; if (isGray) { ConvertBitmapSource.DestinationFormat = PixelFormats.Gray32Float; } ConvertBitmapSource.EndInit(); string NameAchievement = ListAchievements[i].Name; ListBoxAchievements.Add(new listAchievements() { Name = NameAchievement, DateUnlock = dateUnlock, Icon = ConvertBitmapSource, Description = ListAchievements[i].Description }); iconImage = null; } // Sorting default. lbAchievements.ItemsSource = ListBoxAchievements; CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(lbAchievements.ItemsSource); view.SortDescriptions.Add(new SortDescription("DateUnlock", ListSortDirection.Descending)); }
public Bgra32Image ToBgra32Image() { var bitmap = new FormatConvertedBitmap(ToBitmapSource(), PixelFormats.Bgra32, null, 0); return(new Bgra32Image(bitmap)); }
public static WriteableBitmap ConvertToPbgra32(WriteableBitmap src) { FormatConvertedBitmap bmpSrc = new FormatConvertedBitmap(src, PixelFormats.Pbgra32, null, 0); return(new WriteableBitmap(bmpSrc)); }
private byte[] BulidPixels(FormatConvertedBitmap values) { byte[] imgPixels = new byte[16 * 16]; values.CopyPixels(imgPixels, 16, 0); return(imgPixels); }
public Depthmap(BitmapSource source) { // Always convert to greyscale Bitmap = new FormatConvertedBitmap(source, PixelFormats.Gray8, null, 0.0); }
/// <summary> /// Handles the Tick event of the timer control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void timer_Tick(object sender, EventArgs e) { // If we don't have a scene, we're done. if (Scene == null) { return; } // Lock on the Scene. lock (Scene) { // Start the stopwatch so that we can time the rendering. stopwatch.Restart(); // Draw the scene. Scene.Draw(Camera); // Draw the FPS. if (DrawFPS) { Scene.OpenGL.DrawText(5, 5, 1.0f, 0.0f, 0.0f, "Courier New", 12.0f, string.Format("Draw Time: {0:0.0000} ms ~ {1:0.0} FPS", frameTime, 1000.0 / frameTime)); Scene.OpenGL.Flush(); } if (Scene.OpenGL.RenderContextProvider is RenderContextProviders.DIBSectionRenderContextProvider) { RenderContextProviders.DIBSectionRenderContextProvider provider = Scene.OpenGL.RenderContextProvider as RenderContextProviders.DIBSectionRenderContextProvider; // TODO: We have to remove the alpha channel - for some reason it comes out as 0.0 // meaning the drawing comes out transparent. FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap(); newFormatedBitmapSource.BeginInit(); newFormatedBitmapSource.Source = BitmapConversion.HBitmapToBitmapSource(provider.DIBSection.HBitmap); newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24; newFormatedBitmapSource.EndInit(); // Copy the pixels over. image.Source = newFormatedBitmapSource; } else if (Scene.OpenGL.RenderContextProvider is RenderContextProviders.FBORenderContextProvider) { RenderContextProviders.FBORenderContextProvider provider = Scene.OpenGL.RenderContextProvider as RenderContextProviders.FBORenderContextProvider; // TODO: We have to remove the alpha channel - for some reason it comes out as 0.0 // meaning the drawing comes out transparent. FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap(); newFormatedBitmapSource.BeginInit(); newFormatedBitmapSource.Source = BitmapConversion.HBitmapToBitmapSource(provider.InternalDIBSection.HBitmap); newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24; newFormatedBitmapSource.EndInit(); // Copy the pixels over. image.Source = newFormatedBitmapSource; } // Stop the stopwatch. stopwatch.Stop(); // Store the frame time. frameTime = stopwatch.Elapsed.TotalMilliseconds; } }
private void CreateAndShowMainWindow() { // Create the application's main window mainWindow = new Window(); mainWindow.Title = "CachedBitmap Imaging Sample"; // Create a BitmapSource using a Uri BitmapSource source = BitmapFrame.Create(new Uri("tulipfarm.jpg", UriKind.RelativeOrAbsolute)); // Create a new BitmapSource by scaling the original one. //<Snippet1> TransformedBitmap scaledSource = new TransformedBitmap(); scaledSource.BeginInit(); scaledSource.Source = source; scaledSource.Transform = new ScaleTransform(5, 5, 25, 25); scaledSource.EndInit(); //</Snippet1> // Create a cache for the scaled BitmapSource // OnLoad will create the cache as soon as the new BitmapSource is created. //<Snippet4> //<Snippet2> CachedBitmap cachedSource = new CachedBitmap( scaledSource, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); //</Snippet2> //<Snippet3> // Create a new BitmapSource using a different format than the original one. FormatConvertedBitmap newFormatSource = new FormatConvertedBitmap(); newFormatSource.BeginInit(); newFormatSource.Source = cachedSource; newFormatSource.DestinationFormat = PixelFormats.Gray32Float; newFormatSource.EndInit(); //</Snippet3> //</Snippet4> // Define an Image Control to host the FormatConvertedImage Image myImage = new Image(); myImage.Source = newFormatSource; // Define a StackPanel to host Content StackPanel myStackPanel = new StackPanel(); myStackPanel.Orientation = Orientation.Vertical; myStackPanel.VerticalAlignment = VerticalAlignment.Stretch; myStackPanel.HorizontalAlignment = HorizontalAlignment.Stretch; // Add the Image and TextBlock to the parent Grid myStackPanel.Children.Add(myImage); // Add the StackPanel as the Content of the Parent Window Object mainWindow.Content = myStackPanel; mainWindow.Show(); }
private void HandleTick(object sender, EventArgs e) { IntPoint mousePoint = NativeMethods.GetCursorPos(); if (mousePoint == this.lastMousePoint && DateTime.Now - this.lastCapture < TimeSpan.FromSeconds(.2)) { return; } this.lastCapture = DateTime.Now; this.lastMousePoint = mousePoint; this.MouseX.Text = string.Format(@"X: {0}", mousePoint.X - this.basePoint.X); this.MouseY.Text = string.Format(@"Y: {0}", mousePoint.Y - this.basePoint.Y); if (this.isPaused) { return; } double width = this.Image.ActualWidth / this.Scale; double height = this.Image.ActualHeight / this.Scale; double left = (mousePoint.X - width / 2).Clamp(ScreenShot.FullScreenBounds.Left, ScreenShot.FullScreenBounds.Width - width); double top = (mousePoint.Y - height / 2).Clamp(ScreenShot.FullScreenBounds.Top, ScreenShot.FullScreenBounds.Height - height); double deltaX = left - (mousePoint.X - width / 2); double deltaY = top - (mousePoint.Y - height / 2); if (deltaX != 0) { this.CenterX.Width = new GridLength((this.Image.ActualWidth / 2 - deltaX * this.Scale) + 2 * this.Scale); } else { this.CenterX.Width = new GridLength(this.Image.ActualWidth / 2 + 8); } if (deltaY != 0) { this.CenterY.Height = new GridLength((this.Image.ActualHeight / 2 - deltaY * this.Scale) + 2 * this.Scale); } else { this.CenterY.Height = new GridLength(this.Image.ActualHeight / 2 + 8); } IntRect rect = new IntRect((int)left, (int)top, (int)width, (int)height); ScreenShot screenShot = new ScreenShot(rect); FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap(); newFormatedBitmapSource.BeginInit(); newFormatedBitmapSource.Source = screenShot.Image; newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24; newFormatedBitmapSource.EndInit(); this.Image.Source = newFormatedBitmapSource; if (width == 0 || height == 0) { return; } uint centerPixel = (uint)screenShot.GetScreenPixel((int)mousePoint.X, (int)mousePoint.Y); centerPixel = centerPixel | 0xFF000000; byte r = (byte)((centerPixel >> 16) & 0xFF); byte g = (byte)((centerPixel >> 8) & 0xFF); byte b = (byte)((centerPixel >> 0) & 0xFF); Brush brush = new SolidColorBrush(Color.FromRgb(r, g, b)); this.ColorSwatch.Fill = brush; this.PixelColor.Text = string.Format(@"#{0:X8}", centerPixel); }
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 static WriteableBitmap ConvertToBgra32Format(WriteableBitmap oldFormatBitmap) { var convertedBitmap = new FormatConvertedBitmap(oldFormatBitmap, PixelFormats.Bgra32, null, 0); return(new WriteableBitmap(convertedBitmap)); }
//--------------------------------------------------------------------------- /** * @fn public void fn_SaveImage(string strPath) * @brief Image Save. * @return void * @param string strPath : Image Path. * @remark * - * @author 선경규(Kyeong Kyu - Seon) * @date 2020/3/9 18:34 */ public void fn_SaveImage(string strPath, bool bOrigin = false, bool bRender = false) { Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate() { if (m_ImgBrs != null) { try { WriteableBitmap bmp; if (bOrigin) { bmp = m_ImgBrsOrg.ImageSource as WriteableBitmap; } else { bmp = m_ImgBrs.ImageSource as WriteableBitmap; } if (bRender) { Transform transform = lib_Canvas.LayoutTransform; lib_Canvas.LayoutTransform = null; Size size = new Size(lib_Canvas.Width, lib_Canvas.Height); Size back = lib_Canvas.DesiredSize; lib_Canvas.Measure(size); lib_Canvas.Arrange(new Rect(size)); RenderTargetBitmap rb = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96d, 96d, PixelFormats.Default); rb.Render(lib_Canvas); FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap(); newFormatedBitmapSource.BeginInit(); newFormatedBitmapSource.Source = rb; newFormatedBitmapSource.DestinationFormat = bmp.Format; newFormatedBitmapSource.EndInit(); using (FileStream stream = new FileStream(strPath, FileMode.Create)) { //PngBitmapEncoder encoder = new PngBitmapEncoder(); BmpBitmapEncoder encoder = new BmpBitmapEncoder(); //encoder.Frames.Add(BitmapFrame.Create(bmp)); encoder.Frames.Add(BitmapFrame.Create(newFormatedBitmapSource)); encoder.Save(stream); } lib_Canvas.Measure(back); lib_Canvas.LayoutTransform = transform; } else { using (FileStream stream = new FileStream(strPath, FileMode.Create)) { //PngBitmapEncoder encoder = new PngBitmapEncoder(); BmpBitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bmp)); encoder.Save(stream); } } } catch (Exception ex) { delwritelog?.Invoke($"{this.Title} : {ex.Message}"); } } })); }
private static BitmapSource SharpenFixedByCanvas(BitmapSource input, int width, int height) { if (input.PixelWidth == width && input.PixelHeight == height) { return(input); } if (input.Format != PixelFormats.Bgra32 || input.Format != PixelFormats.Pbgra32) { input = new FormatConvertedBitmap(input, PixelFormats.Bgra32, null, 0); } //Use the same scale for x and y to keep aspect ratio. double scale = Math.Min((double)width / input.PixelWidth, height / (double)input.PixelHeight); int x = (int)Math.Round((width - (input.PixelWidth * scale)) / 2); int y = (int)Math.Round((height - (input.PixelHeight * scale)) / 2); var scaled = new TransformedBitmap(input, new ScaleTransform(scale, scale)); var stride = scaled.PixelWidth * (scaled.Format.BitsPerPixel / 8); #region Make a WhiteCanvas List <System.Windows.Media.Color> colors = new List <System.Windows.Media.Color>(); colors.Add(System.Windows.Media.Colors.White); BitmapPalette palette = new BitmapPalette(colors); System.Windows.Media.PixelFormat pf = System.Windows.Media.PixelFormats.Indexed1; int strideWhite = width / pf.BitsPerPixel; byte[] pixels = new byte[height * strideWhite]; for (int i = 0; i < height * strideWhite; ++i) { pixels[i] = 0x00; } BitmapSource whiteimage = BitmapSource.Create( width, height, 96, 96, pf, palette, pixels, strideWhite); #endregion #region ResizeImage + WhiteCanvas // Create a render bitmap and push the surface to it var target = new RenderTargetBitmap(width, height, whiteimage.DpiX, whiteimage.DpiY, PixelFormats.Default); var targetVisual = new DrawingVisual(); var targetContext = targetVisual.RenderOpen(); //targetContext.DrawImage(scaled, new System.Windows.Rect(0, 0, scaled.Width, scaled.Height)); //ImageDrawing targetContext.DrawImage(scaled, new System.Windows.Rect(0, 0, scaled.PixelWidth, scaled.PixelHeight)); //ImageDrawing targetContext.Close(); target.Render(targetVisual); // Adding those two render bitmap to the same drawing visual var resultBitmap = new RenderTargetBitmap(width, height, whiteimage.DpiX, whiteimage.DpiY, PixelFormats.Default); DrawingVisual dv = new DrawingVisual(); DrawingContext dc = dv.RenderOpen(); dc.DrawImage(whiteimage, new System.Windows.Rect(0, 0, width, height)); int posTx = (whiteimage.PixelWidth - scaled.PixelWidth) / 2; int posTy = (whiteimage.PixelHeight - scaled.PixelHeight) / 2; dc.DrawImage(target, new System.Windows.Rect(posTx, posTy, width, height)); dc.Close(); resultBitmap.Render(dv); #endregion #region MediaBitmap to DrawingBitmap - Result Image MemoryStream ms = new MemoryStream(); var encoder = new System.Windows.Media.Imaging.BmpBitmapEncoder(); encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(resultBitmap)); encoder.Save(ms); ms.Flush(); System.Drawing.Image gdiImage = System.Drawing.Image.FromStream(ms); #endregion return(ToBitmapImage(ApplySharpen((double)width, (System.Drawing.Bitmap)gdiImage))); //ShapenImage //return scaled; //return resultBitmap; }