private void CreateBuffer() { IntPtr handleScreenDC = NativeMethods.GetDC(IntPtr.Zero); handleBitmapDC = NativeMethods.CreateCompatibleDC(handleScreenDC); NativeMethods.ReleaseDC(IntPtr.Zero, handleScreenDC); bufferSize = size; BitmapInfo info = new BitmapInfo(); info.Size = Marshal.SizeOf(info); info.Width = size.Width; info.Height = -size.Height; info.BitCount = 32; info.Planes = 1; IntPtr ptr; IntPtr hBmp = NativeMethods.CreateDIBSection(handleBitmapDC, ref info, 0, out ptr, IntPtr.Zero, 0); IntPtr hBmpOld = NativeMethods.SelectObject(handleBitmapDC, hBmp); NativeMethods.DeleteObject(hBmpOld); graphics = Graphics.FromHdc(handleBitmapDC); if (Environment.OSVersion.Version.Major > 5) { this.graphics.TextRenderingHint = TextRenderingHint.SystemDefault; this.graphics.SmoothingMode = SmoothingMode.HighQuality; } }
void IRenderWebBrowser.InvokeRenderAsync(BitmapInfo bitmapInfo) { UiThreadRunAsync(delegate { lock (bitmapInfo.BitmapLock) { var wpfBitmapInfo = (WpfBitmapInfo)bitmapInfo; // Inform parents that the browser rendering is updating OnRendering(this, wpfBitmapInfo); // Now update the WPF image if (wpfBitmapInfo.CreateNewBitmap) { var img = bitmapInfo.IsPopup ? popupImage : image; img.Source = null; GC.Collect(1); img.Source = wpfBitmapInfo.CreateBitmap(); } wpfBitmapInfo.Invalidate(); } }, DispatcherPriority.Render); }
void IRenderWebBrowser.InvokeRenderAsync(BitmapInfo bitmapInfo) { UiThreadRunAsync(delegate { lock (bitmapInfo.BitmapLock) { var interopBitmapInfo = (InteropBitmapInfo)bitmapInfo; // Inform parents that the browser rendering is updating OnRendering(this, interopBitmapInfo); // Now update the WPF image var bitmap = interopBitmapInfo.InteropBitmap; if (bitmap == null) { var img = bitmapInfo.IsPopup ? popupImage : image; img.Source = null; GC.Collect(1); var stride = bitmapInfo.Width * bitmapInfo.BytesPerPixel; bitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(bitmapInfo.FileMappingHandle, bitmapInfo.Width, bitmapInfo.Height, PixelFormat, stride, 0); img.Source = bitmap; interopBitmapInfo.InteropBitmap = bitmap; } bitmap.Invalidate(); } }, DispatcherPriority.Render); }
public static int Add(Bitmap Bitmap, ImageList ImageList) { IntPtr hBitmap; IntPtr ppvBits; BitmapInfo bitmapInfo = new BitmapInfo(); // Make a copy of the bitmap. We are are going to flip it and don't want the // original file to be modified. This solves another problem en-passant // where bitmap and image list size differ. Bitmap = new Bitmap(Bitmap, ImageList.ImageSize.Width, ImageList.ImageSize.Height); bitmapInfo.biSize = 40; bitmapInfo.biBitCount = 32; bitmapInfo.biPlanes = 1; bitmapInfo.biWidth = Bitmap.Width; bitmapInfo.biHeight = Bitmap.Height; Bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY); hBitmap = CreateDIBSection(new IntPtr(0), bitmapInfo, 0, out ppvBits, new IntPtr(0), 0); BitmapData bitmapData = Bitmap.LockBits( new Rectangle(0, 0, Bitmap.Width, Bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); RtlMoveMemory(ppvBits, bitmapData.Scan0, Bitmap.Height * bitmapData.Stride); Bitmap.UnlockBits(bitmapData); ImageList_Add(ImageList.Handle, hBitmap, new IntPtr(0)); return(ImageList.Images.Count - 1); }
/// <summary> /// Invoked from CefRenderHandler.OnPaint /// A new <see cref="Bitmap" /> is only created when <see cref="BitmapInfo.CreateNewBitmap" /> /// is true, otherwise the new buffer is simply copied into the backBuffer of the existing /// <see cref="Bitmap" /> for efficiency. Locking provided by OnPaint as this method is called /// in it's lock scope. /// </summary> /// <param name="bitmapInfo">information about the bitmap to be rendered</param> void IRenderWebBrowser.OnPaint(BitmapInfo bitmapInfo) { var handled = false; var handler = OnPaint; if (handler != null) { var args = new OnPaintEventArgs(bitmapInfo.IsPopup, bitmapInfo.DirtyRect, bitmapInfo.BackBufferHandle, bitmapInfo.Width, bitmapInfo.Height, bitmapInfo.BytesPerPixel, bitmapInfo.NumberOfBytes); handler(this, args); handled = args.Handled; } if (!handled) { var newScreenshotHandler = NewScreenshot; if (newScreenshotHandler != null) { newScreenshotHandler(this, EventArgs.Empty); } InvokeRenderAsync(bitmapInfo); } }
public static int Add(Bitmap Bitmap, ImageList ImageList) { IntPtr hBitmap; IntPtr ppvBits; BitmapInfo bitmapInfo = new BitmapInfo(); // Make a copy of the bitmap. We are are going to flip it and don't want the // original file to be modified. This solves another problem en-passant // where bitmap and image list size differ. Bitmap = new Bitmap(Bitmap, ImageList.ImageSize.Width, ImageList.ImageSize.Height); bitmapInfo.biSize = 40; bitmapInfo.biBitCount = 32; bitmapInfo.biPlanes = 1; bitmapInfo.biWidth = Bitmap.Width; bitmapInfo.biHeight = Bitmap.Height; Bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY); hBitmap = CreateDIBSection(new IntPtr(0), bitmapInfo, 0, out ppvBits, new IntPtr(0), 0); BitmapData bitmapData = Bitmap.LockBits( new Rectangle(0, 0, Bitmap.Width, Bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); RtlMoveMemory(ppvBits, bitmapData.Scan0, Bitmap.Height * bitmapData.Stride); Bitmap.UnlockBits(bitmapData); ImageList_Add(ImageList.Handle, hBitmap, new IntPtr(0)); return ImageList.Images.Count - 1; }
protected override void FillPixelData(BitmapInfo bitmapInfoSource, BitmapInfo bitmapInfoDest) { for (int y = 0; y < bitmapInfoSource.Height; y++) { for (int x = 0; x < bitmapInfoSource.Width; x++) { Color sourceColor = bitmapInfoSource.GetPixelColor(x, y); //float hue = sourceColor.GetHue(); //float saturation = sourceColor.GetSaturation(); //float brightness = sourceColor.GetBrightness(); //double hue, saturation, value; //ColorToHSV(sourceColor, out hue, out saturation, out value); double hue, saturation, lightness; RGBtoHSL(sourceColor, out hue, out saturation, out lightness); double transmittance = GetTransmittance(hue); double newLightness = transmittance * lightness; // we do not preserve lightness Color filteredColor = HSLtoRGB(hue, saturation, newLightness); bitmapInfoDest.SetPixelColor(x, y, filteredColor); } } }
public static extern IntPtr CreateDIBSection( IntPtr hdc, [In] ref BitmapInfo pbmi, uint iUsage, out IntPtr ppvBits, IntPtr hSection, uint dwOffset);
/// <summary> /// Invoked from CefRenderHandler.OnPaint /// A new <see cref="Bitmap" /> is only created when <see cref="BitmapInfo.CreateNewBitmap" /> /// is true, otherwise the new buffer is simply copied into the backBuffer of the existing /// <see cref="Bitmap" /> for efficiency. Locking provided by OnPaint as this method is called /// in it's lock scope. /// </summary> /// <param name="bitmapInfo">information about the bitmap to be rendered</param> public virtual void InvokeRenderAsync(BitmapInfo bitmapInfo) { var gdiBitmapInfo = (GdiBitmapInfo)bitmapInfo; if (bitmapInfo.CreateNewBitmap) { if (gdiBitmapInfo.IsPopup) { if (Popup != null) { Popup.Dispose(); Popup = null; } Popup = gdiBitmapInfo.CreateBitmap(); } else { if (Bitmap != null) { Bitmap.Dispose(); Bitmap = null; } Bitmap = gdiBitmapInfo.CreateBitmap(); } } }
public GdiBitmap(int width, int height) { Width = width; Height = height; DeviceContext = Gdi32.CreateCompatibleDC(IntPtr.Zero); var bitmapHeader = new BitmapInfoHeader { biSize = (uint)Marshal.SizeOf <BitmapInfoHeader>(), biWidth = width, biHeight = -height, // negative, top-down bitmap biPlanes = 1, biBitCount = (ushort)(8 * BytesPerPixel), biCompression = BitmapCompression.BI_RGB, }; var bitmapInfo = new BitmapInfo { bmiHeader = bitmapHeader, }; BitmapHandle = Gdi32.CreateDIBSection(DeviceContext, in bitmapInfo, ColorUsage.DIB_RGB_COLORS, out BitmapData, IntPtr.Zero, 0); _oldObject = Gdi32.SelectObject(DeviceContext, BitmapHandle); }
// *********************** public void Draw(BoundingArea.ReadOnly bounding_area, params IDrawableObject[] drawable_objects) { Utils.ThrowException(bounding_area == null ? new ArgumentNullException("bounding_area") : null); Utils.ThrowException(drawable_objects == null ? new ArgumentNullException("drawable_objects") : null); DateTime start_time = DateTime.Now; BoundingArea extended_area = bounding_area.GetWritableCopy(); ExtendBoundingArea(extended_area, drawable_objects); #if !NO_BB_SIMPLIFICATION extended_area.Optimize(); #endif TransformParams tr = new TransformParams(0, 0, m_scale_factor); Set <IDrawableObject> outdated_objects = new Set <IDrawableObject>(drawable_objects); drawable_objects = m_drawable_object.GetObjectsIn(extended_area, tr); Rectangle enclosing_rect = GetEnclosingRect(extended_area.BoundingBox); BitmapInfo render_layer = PrepareBitmap(RENDER_LAYER, enclosing_rect.Width, enclosing_rect.Height); TransformParams render_tr = new TransformParams(-enclosing_rect.X, -enclosing_rect.Y, m_scale_factor); BoundingArea extended_area_tr = extended_area.Clone(); extended_area_tr.Transform(new TransformParams(-enclosing_rect.X, -enclosing_rect.Y, 1)); for (int i = drawable_objects.Length - 1; i >= 0; i--) { if (outdated_objects.Contains(drawable_objects[i])) { drawable_objects[i].Draw(render_layer.Graphics, render_tr); } else { drawable_objects[i].Draw(render_layer.Graphics, render_tr, extended_area_tr); } } BitmapInfo main_layer = m_bmp_cache[MAIN_LAYER]; Graphics canvas_gfx = Graphics.FromHwnd(picBoxCanvas.Handle); foreach (RectangleF rect in extended_area.Rectangles) { Rectangle view_area = GetEnclosingRect(rect); view_area.X -= enclosing_rect.X; view_area.Y -= enclosing_rect.Y; view_area.Intersect(new Rectangle(0, 0, enclosing_rect.Width, enclosing_rect.Height)); EditableBitmap view = render_layer.EditableBitmap.CreateView(view_area); main_layer.Graphics.DrawImageUnscaled(view.Bitmap, view_area.X + enclosing_rect.X, view_area.Y + enclosing_rect.Y); // clipping to visible area?!? canvas_gfx.DrawImageUnscaled(view.Bitmap, view_area.X + enclosing_rect.X, view_area.Y + enclosing_rect.Y); //view_on_view.Dispose(); view.Dispose(); } canvas_gfx.Dispose(); TimeSpan draw_time = DateTime.Now - start_time; m_draw_time += draw_time; m_draw_count++; FpsInfo.Text = string.Format("{0:0.00} ms / draw", (double)m_draw_time.TotalMilliseconds / (double)m_draw_count); m_draw_info.Add(draw_time.TotalMilliseconds); FpsInfo.Refresh(); }
public static unsafe PointerBitmap AsPointerBitmap(AVFrame frame) { _EnsureBinariesAreSet(); var binfo = new BitmapInfo(frame.width, frame.height, Pixel.BGR24.Format, frame.linesize[0]); return(new PointerBitmap((IntPtr)frame.data[0], binfo, true)); }
public BitmapInfo GetFilteredImage(BitmapInfo bitmapInfoSource) { BitmapInfo result = new BitmapInfo( bitmapInfoSource.Width, bitmapInfoSource.Height, bitmapInfoSource.PixelFormat); FillPixelData(bitmapInfoSource, result); return(result); }
private BitmapInfo ReadBitmapInfo(BinaryReader br) { BitmapInfo BI = new BitmapInfo(); BI.bih.biSize = br.ReadUInt32(); BI.bih.biWidth = br.ReadInt32(); BI.bih.biHeight = br.ReadInt32(); BI.bih.biPlanes = br.ReadUInt16(); BI.bih.biBitCount = br.ReadUInt16(); BI.bih.biCompression = br.ReadUInt32(); BI.bih.biSizeImage = br.ReadUInt32(); BI.bih.biXPelsPerMeter = br.ReadInt32(); BI.bih.biYPelsPerMeter = br.ReadInt32(); BI.bih.biClrUsed = br.ReadUInt32(); BI.bih.biClrImportant = br.ReadUInt32(); uint colourCount = 256; if (BI.bih.biClrUsed == 0) { if (BI.bih.biBitCount == 24) { colourCount = 0; } else if (BI.bih.biBitCount == 8) { colourCount = 256; } else if (BI.bih.biBitCount == 1) { colourCount = 2; } else if (BI.bih.biBitCount == 4) { colourCount = 16; } else { colourCount = 0; } } else { colourCount = BI.bih.biClrUsed; } if (colourCount > 0) { BI.bmiColours = new Int32[colourCount]; for (int i = 0; i < colourCount; i++) { BI.bmiColours[i] = br.ReadInt32(); } } return(BI); }
internal WPFFactory(BitmapInfo binfo) { _Info = binfo; if (!_Implementation.TryGetExactPixelFormat(binfo.PixelFormat, out _Exact)) { throw new Diagnostics.PixelFormatNotSupportedException(binfo.PixelFormat, nameof(binfo)); } }
public static void DownscaleTextureInfo(TargetPlatform platform, BitmapInfo textureInfo, string path, CookingRules rules) { int newHeight; int newWidth; DownscaleTextureHelper(platform, textureInfo.Width, textureInfo.Height, path, rules, out newWidth, out newHeight); textureInfo.Height = newHeight; textureInfo.Width = newWidth; }
protected override Bitmap Transcode(BitmapInfo bitmapInfo, EncodingInfo imageEncoding, IProgress <ProgressReport> progress) { var img = bitmapInfo.Image; var settings = new ImageSettings(BTX.Encodings[imageEncoding.EncodingIndex], img.Width, img.Height); var data = Kanvas.Kolors.Save(img, settings); _format.Texture = Kanvas.Kolors.Load(data, settings); return(_format.Texture); }
/// <exception cref="System.ArgumentNullException">bitmapInfo is null.</exception> public bool Supports(BitmapInfo bitmapInfo) { if (bitmapInfo == null) { throw new ArgumentNullException(nameof(bitmapInfo)); } return(ICSendMessage(_hic, IcMessage.CompressQuery, bitmapInfo.RawData, IntPtr.Zero) == IntPtr.Zero); }
public Bitmap PopulateToBitmap() { Bitmap outputBitmap = new Bitmap(BoundaryRect.Width, BoundaryRect.Height, Bitmap.PixelFormat); var outputInfo = new BitmapInfo(outputBitmap); Marshal.Copy(RgbValues, 0, outputInfo.Ptr, BitmapSize); outputInfo.Dispose(); return(outputInfo.Bitmap); }
public override string ToString() { return(string.Format(CultureInfo.CurrentCulture, "VIDEOINFOHEADER - Source: {0} Target: {1} BitRate: {2} " + "BitErrorRate: {3} AvgTimePerFrame: {4}\r\n{5}", Source.ToString(), Target.ToString(), BitRate, BitErrorRate, AvgTimePerFrame, BitmapInfo.ToString())); }
public EncodeImageViewModel(FileManager fileManager, IImageAdapter adapter, BitmapInfo bitmapInfo) { _fileManager = fileManager; _adapter = adapter; _bitmapInfo = bitmapInfo; SelectedEncoding = _bitmapInfo.ImageEncoding; SourceImage = _bitmapInfo.Image.ToBitmapImage(true); OutputImage = SourceImage; }
private void SetupCanvas(int width, int height) { if (canvas_view != null) { canvas_view.Dispose(); } BitmapInfo main_layer = m_bmp_cache[MAIN_LAYER]; canvas_view = main_layer.EditableBitmap.CreateView(new Rectangle(0, 0, width, height)); }
public static void DownscaleTextureToFitAtlas(BitmapInfo textureInfo, string path) { int newWidth; int newHeight; if (DownscaleTextureToFitAtlasHelper(textureInfo.Width, textureInfo.Height, path, out newWidth, out newHeight)) { textureInfo.Width = newWidth; textureInfo.Height = newHeight; } }
public static bool TryGetBitmapInfo(ANDROIDGFX.AndroidBitmapInfo src, bool srcIsPremultiplied, out BitmapInfo dst) { if (TryGetPixelFormat(src.Format, srcIsPremultiplied, out var dstFmt)) { dst = new BitmapInfo((int)src.Width, (int)src.Height, dstFmt, (int)src.Stride); return(true); } dst = default; return(false); }
public static bool TryGetBitmapInfo(Image image, out BitmapInfo binfo) { if (TryGetExactPixelFormat(image, out var fmt)) { binfo = new BitmapInfo(image.Width, image.Height, fmt); return(true); } binfo = default; return(false); }
/// <summary> /// Invoked from CefRenderHandler.OnPaint /// A new <see cref="Bitmap" /> is only created when <see cref="BitmapInfo.CreateNewBitmap" /> /// is true, otherwise the new buffer is simply copied into the backBuffer of the existing /// <see cref="Bitmap" /> for efficiency. Locking provided by OnPaint as this method is called /// in it's lock scope. /// </summary> /// <param name="bitmapInfo">information about the bitmap to be rendered</param> void IRenderWebBrowser.InvokeRenderAsync(BitmapInfo bitmapInfo) { InvokeRenderAsync(bitmapInfo); var handler = NewScreenshot; if (handler != null) { handler(this, EventArgs.Empty); } }
internal AndroidFactory(BitmapInfo binfo, ANDROIDBITMAP.Config defFmt = null) { if (defFmt == null) { defFmt = ANDROIDBITMAP.Config.Argb8888; } _Info = binfo; _Exact = _Implementation.ToAndroidBitmapConfig(_Info.PixelFormat, null); _Compatible = _Implementation.ToAndroidBitmapConfig(_Info.PixelFormat, defFmt); }
void IRenderWebBrowser.ClearBitmap(BitmapInfo bitmapInfo) { lock (bitmapLock) { if (bitmap != null) { bitmap.Dispose(); } bitmap = null; } }
public static SpanBitmap GetSpanBitmap <T>(IDenseTensor <T> tensor) where T : unmanaged { var dims = tensor.Dimensions; var width = dims[2]; var height = dims[1]; var fmt = PixelFormat.CreateFromDepthAndChannels(typeof(T), dims[3]); var info = new BitmapInfo(width, height, fmt); var data = System.Runtime.InteropServices.MemoryMarshal.Cast <T, Byte>(tensor.Span); return(new SpanBitmap(data, info)); }
protected void SetSnapshotBitmap(BitmapInfo bitmapInfo) { var stride = bitmapInfo.Width * ((IRenderWebBrowser)this).BytesPerPixel; lock (bitmapInfo.BitmapLock) { var snapshotBitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(bitmapInfo.FileMappingHandle, bitmapInfo.Width, bitmapInfo.Height, PixelFormat, stride, 0); SaveBitmapAsPng(snapshotBitmap, _snapshotFile); _snapshotIsComplete.Set(); } }
public static bool TryGetBitmapInfo <TPixel>(Image <TPixel> image, out BitmapInfo binfo) where TPixel : unmanaged, IPixel <TPixel> { if (TryGetExactPixelFormat <TPixel>(out var fmt)) { binfo = new BitmapInfo(image.Width, image.Height, fmt); return(true); } binfo = default; return(false); }
private static extern int GetDIBits(IntPtr hdc, IntPtr hbmp, uint uStartScan, uint cScanLines, [Out] IntPtr lpvBits, ref BitmapInfo lpbmi, uint uUsage);
private object SetBitmapHelper(BitmapInfo bitmapInfo, InteropBitmap bitmap, Action<InteropBitmap> imageSourceSetter) { if (bitmap == null) { imageSourceSetter(null); GC.Collect(1); var stride = bitmapInfo.Width * BytesPerPixel; bitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(bitmapInfo.FileMappingHandle, bitmapInfo.Width, bitmapInfo.Height, PixelFormat, stride, 0); imageSourceSetter(bitmap); } bitmap.Invalidate(); return bitmap; }
/// <summary> /// The read h 2 parsed bitmap. /// </summary> /// <param name="meta">The meta.</param> /// <remarks></remarks> public void ReadH2ParsedBitmap(ref Meta meta) { BinaryReader BR = new BinaryReader(meta.MS); BR.BaseStream.Position = 68; int tempc = BR.ReadInt32(); int tempr = BR.ReadInt32() - meta.Map.SecondaryMagic - meta.offset; headersize = tempr; Properties = new BitmapInfo[tempc]; int okay = -1; for (int x = 0; x < tempc; x++) { Properties[x] = new BitmapInfo(tempr + (116 * x), ref meta); if (Properties[x].bitsPerPixel == 0) { okay = x; } if (Properties[x].format == 23) { } } if (okay != -1) { MessageBox.Show( Properties[okay].formatname + "\nFormat not supported, please inform developer of above format name."); } }
/// <summary> /// The read ce parsed bitmap. /// </summary> /// <param name="meta">The meta.</param> /// <remarks></remarks> public void ReadCEParsedBitmap(ref Meta meta) { using (BinaryReader BR = new BinaryReader(meta.MS)) { int tempr; if (meta.Map.MetaInfo.external[meta.TagIndex]) { BR.BaseStream.Position = 96; int tempc = BR.ReadInt32(); tempr = BR.ReadInt32(); headersize = tempr; Properties = new BitmapInfo[tempc]; for (int x = 0; x < tempc; x++) { Properties[x] = new BitmapInfo(tempr + (48 * x), ref meta); } } else { BR.BaseStream.Position = 96; int tempc = BR.ReadInt32(); tempr = BR.ReadInt32() - meta.Map.PrimaryMagic - meta.Map.MetaInfo.Offset[meta.TagIndex]; headersize = tempr; Properties = new BitmapInfo[tempc]; for (int x = 0; x < tempc; x++) { Properties[x] = new BitmapInfo(tempr + (48 * x), ref meta); } } } }
public void ClearBitmap(BitmapInfo bitmapInfo) { bitmapInfo.InteropBitmap = null; }
private void AddPNGToImageList(ImageList imageList, string fileName) { Bitmap bitmap = new Bitmap(GetImage(fileName, ImageSize.M22)); IntPtr hBitmap, ppvBits; BitmapInfo bitmapInfo = new BitmapInfo(); bitmapInfo.biSize = 40; bitmapInfo.biBitCount = 32; bitmapInfo.biPlanes = 1; bitmapInfo.biWidth = bitmap.Width; bitmapInfo.biHeight = bitmap.Height; bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY); hBitmap = CreateDIBSection(new IntPtr(0), bitmapInfo, 0, out ppvBits, new IntPtr(0), 0); Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height); BitmapData bitmapData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); IntPtr pixels = bitmapData.Scan0; RtlMoveMemory(ppvBits, pixels, bitmap.Height * bitmapData.Stride); bitmap.UnlockBits(bitmapData); ImageList_Add(imageList.Handle, hBitmap, new IntPtr(0)); }
/// <summary> /// Copies a bitmap into a 1bpp/8bpp bitmap of the same dimensions, fast /// </summary> /// <param name="b">original bitmap</param> /// <param name="bpp">1 or 8, target bpp</param> /// <returns>a 1bpp copy of the bitmap</returns> public static Bitmap CopyToBpp(Bitmap b, int bpp) { if (bpp != 1 && bpp != 8) throw new ArgumentException("1 or 8", "bpp"); // Plan: built into Windows GDI is the ability to convert // bitmaps from one format to another. Most of the time, this // job is actually done by the graphics hardware accelerator card // and so is extremely fast. The rest of the time, the job is done by // very fast native code. // We will call into this GDI functionality from C#. Our plan: // (1) Convert our Bitmap into a GDI hbitmap (ie. copy unmanaged->managed) // (2) Create a GDI monochrome hbitmap // (3) Use GDI "BitBlt" function to copy from hbitmap into monochrome (as above) // (4) Convert the monochrone hbitmap into a Bitmap (ie. copy unmanaged->managed) int w = b.Width, h = b.Height; IntPtr hbm = b.GetHbitmap(); // this is step (1) // // Step (2): create the monochrome bitmap. // "BitmapInfo" is an interop-struct which we define below. // In GDI terms, it's a BITMAPHEADERINFO followed by an array of two RGBQUADs var bmi = new BitmapInfo { biSize = 40, // the size of the BITMAPHEADERINFO struct biWidth = w, biHeight = h, biPlanes = 1, // "planes" are confusing. We always use just 1. Read MSDN for more info. biBitCount = (short)bpp, // ie. 1bpp or 8bpp biCompression = BI_RGB, // ie. the pixels in our RGBQUAD table are stored as RGBs, not palette indexes biSizeImage = (uint)(((w + 7) & 0xFFFFFFF8) * h / 8), biXPelsPerMeter = 1000000, // not really important biYPelsPerMeter = 1000000 // not really important }; // Now for the colour table. uint ncols = (uint)1 << bpp; // 2 colours for 1bpp; 256 colours for 8bpp bmi.biClrUsed = ncols; bmi.biClrImportant = ncols; bmi.cols = new uint[256]; // The structure always has fixed size 256, even if we end up using fewer colours if (bpp == 1) { bmi.cols[0] = MakeRGB(0, 0, 0); bmi.cols[1] = MakeRGB(255, 255, 255); } else { for (int i = 0; i < ncols; i++) bmi.cols[i] = MakeRGB(i, i, i); } // For 8bpp we've created an palette with just greyscale colours. // You can set up any palette you want here. Here are some possibilities: // greyscale: for (int i=0; i<256; i++) bmi.cols[i]=MakeRGB(i,i,i); // rainbow: bmi.biClrUsed=216; bmi.biClrImportant=216; int[] colv=new int[6]{0,51,102,153,204,255}; // for (int i=0; i<216; i++) bmi.cols[i]=MakeRGB(colv[i/36],colv[(i/6)%6],colv[i%6]); // optimal: a difficult topic: http://en.wikipedia.org/wiki/Color_quantization // // Now create the indexed bitmap "hbm0" IntPtr bits0; // not used for our purposes. It returns a pointer to the raw bits that make up the bitmap. IntPtr hbm0 = CreateDIBSection(IntPtr.Zero, ref bmi, DIB_RGB_COLORS, out bits0, IntPtr.Zero, 0); // // Step (3): use GDI's BitBlt function to copy from original hbitmap into monocrhome bitmap // GDI programming is kind of confusing... nb. The GDI equivalent of "Graphics" is called a "DC". IntPtr sdc = GetDC(IntPtr.Zero); // First we obtain the DC for the screen // Next, create a DC for the original hbitmap IntPtr hdc = CreateCompatibleDC(sdc); SelectObject(hdc, hbm); // and create a DC for the monochrome hbitmap IntPtr hdc0 = CreateCompatibleDC(sdc); SelectObject(hdc0, hbm0); // Now we can do the BitBlt: BitBlt(hdc0, 0, 0, w, h, hdc, 0, 0, SRCCOPY); // Step (4): convert this monochrome hbitmap back into a Bitmap: Bitmap b0 = Image.FromHbitmap(hbm0); b0.SetResolution(b.HorizontalResolution, b.VerticalResolution); // // Finally some cleanup. DeleteDC(hdc); DeleteDC(hdc0); ReleaseDC(IntPtr.Zero, sdc); DeleteObject(hbm); DeleteObject(hbm0); // return b0; }
private static extern IntPtr CreateDIBSection(IntPtr hdc, ref BitmapInfo bmi, uint Usage, out IntPtr bits, IntPtr hSection, uint dwOffset);
public static int NOPH_Bitmap_getBitmapResource(int __name) { String name = "/WazeWP7;component/resources/" + CRunTime.charPtrToString(__name); if (!FileExists(name)) { name = "Userstore://" + CRunTime.charPtrToString(__name); // ignore this file if we can find in in resources. this is usually commercial icon to be located on the map like banks, coffe shops etc. if (!FileExists(name)) { return 0; } } try { Stream stream = GetFileStream(name, FileMode.Open); Texture2D bitmap = GamePage.LoadBitmap(stream); int bitmap_registeredHandle = CRunTime.registerObject(bitmap); BitmapInfo info = new BitmapInfo(bitmap.Width, bitmap.Height); if (!bitmaps_info.ContainsKey(bitmap_registeredHandle)) { bitmaps_info.Add(bitmap_registeredHandle, info); } return bitmap_registeredHandle; } catch(Exception) { // Handle - This XNA Framework graphics operation is not valid when Silverlight rendering is active. To use XNA Framework graphics, call GraphicsDevice.SetDirectRenderingMode(true). // if C code is trying to load hazard picture in XNA while we are showing silverlight search address dialog return 0; } //// Try to get the bitmap from the cache store: //if (bitmapCacheStore.ContainsKey(__name)) //{ // bitmapCacheStore[__name].RegisteredHandle = CRunTime.registerObject(bitmapCacheStore[__name].Bitmap); // bitmaps_info.Add(bitmapCacheStore[__name].RegisteredHandle, bitmapCacheStore[__name].Info); // return bitmapCacheStore[__name].RegisteredHandle; //} }
public static void AddBitmapToPage(IntPtr document, IntPtr page, Image image, BoundsInches imageBounds, int transformationIndex) { Bitmap bitmap = image as Bitmap; BitmapData bi = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat); PixelFormatEnum pf = ConvertPixelFormat_SystemToLibPdfium(bi.PixelFormat); TransformationMatrix matrix = GetTransformationMatrix(imageBounds, transformationIndex); try { unsafe { BitmapInfo info = new BitmapInfo(); info.Height = bitmap.Height; info.Width = bitmap.Width; info.PixelFormat = pf; info.Data = bi.Scan0; info.Stride = bi.Stride; Pdfium.AddBitmapToPage(document, page, &info, &matrix); } } finally { bitmap.UnlockBits(bi); } }
public static WLD Load(Stream stream,string name="default.wld") { WLD wld = new WLD(); wld.Name = name; int size = Marshal.SizeOf(typeof(WLDHeader)); var barray = new byte[size]; stream.Read(barray, 0, size); var header = Functions.ByteArrayToStructure<WLDHeader>(barray); if (header.Magic != 0x54503d02) { throw new Exception("Invalid file format"); } if (header.Version == 0x00015500) { wld._format = Format.Old; } else if (header.Version == 0x1000C800) { wld._format = Format.New; } else { throw new Exception("Unknown file version"); } //var shash = stream.Position; barray = new byte[header.StringHashSize]; stream.Read(barray, 0, (int)header.StringHashSize); wld._sHash = WLD.DecodeFileName(barray); wld._strings = wld._sHash.Split('\0'); var fragCount = header.FragmentCount; stream.Seek(size + header.StringHashSize, SeekOrigin.Begin); int fragSize = Marshal.SizeOf(typeof(BasicWLDFragment)); for (int i = 0; i < header.FragmentCount; i++) { barray = new byte[fragSize]; stream.Read(barray, 0, fragSize); var fragment = Functions.ByteArrayToStructure<BasicWLDFragment>(barray); int nameRef = (int)fragment.NameRef; var position = stream.Position; switch (fragment.Id) { case 0x03: var bmpname = new BitmapName(i, nameRef); bmpname.Handler(stream); wld._fragments.Add(bmpname); break; case 0x04: var binfo = new BitmapInfo(i, nameRef); binfo.Handler(stream); wld._fragments.Add(binfo); break; case 0x05: var bitmapInfoRef = new BitmapInfoReference(i, nameRef); bitmapInfoRef.Handler(stream); wld._fragments.Add(bitmapInfoRef); break; case 0x09: break; case 0x10: var skelset = new SkeletonTrackSet(i, nameRef); skelset.Handler(stream); skelset.FragmentName = wld.GetStringAtHashIndex(0-skelset.FragmentNameRef); wld._fragments.Add(skelset); break; case 0x11: var skeltrackRef = new SkeletonTrackReference(i, nameRef); skeltrackRef.Handler(stream); wld._fragments.Add(skeltrackRef); break; case 0x12: var skelpiece = new SkeletonPieceTrack(i, nameRef); skelpiece.Handler(stream); wld._fragments.Add(skelpiece); break; case 0x13: var skelpref = new SkeletonPieceTrackReference(i, nameRef); skelpref.Handler(stream); //skelpref.FragmentName = wld.GetStringAtHashIndex(0 - skelpref.FragmentNameRef); wld._fragments.Add(skelpref); break; case 0x14: var modelref = new ModelReference(i, nameRef); modelref.Handler(stream); modelref.FragmentName = wld.GetStringAtHashIndex(0 - modelref.FragmentNameRef); wld._fragments.Add(modelref); modelref.MagicString = wld.GetStringAtHashIndex(modelref.MagicStringRef); break; case 0x15: var objlocation = new ObjectLocation(i, nameRef); objlocation.Handler(stream); wld._fragments.Add(objlocation); break; case 0x22: //num_0x22++; break; case 0x2d: var meshref = new MeshReference(i, nameRef); meshref.Handler(stream); wld._fragments.Add(meshref); break; case 0x31: var tlist = new TextureList(i, nameRef); tlist.Handler(stream); wld._fragments.Add(tlist); break; case 0x30: var texture = new Texture(i, nameRef); texture.Handler(stream); wld._fragments.Add(texture); break; // Grab the number of vertices and polygons case 0x36: var mesh = new Mesh(i, nameRef); mesh.Handler(stream); wld._fragments.Add(mesh); break; } stream.Seek(position + fragment.Size - 4, SeekOrigin.Begin); } return wld; }
public void InvokeRenderAsync(Action<BitmapInfo> callback, BitmapInfo bitmapInfo) { if (!Dispatcher.HasShutdownStarted) { Dispatcher.BeginInvoke(DispatcherPriority.Render, callback, bitmapInfo); } }
public void SetBitmap(BitmapInfo bitmapInfo) { lock (bitmapInfo.BitmapLock) { if (bitmapInfo.IsPopup) { bitmapInfo.InteropBitmap = SetBitmapHelper(bitmapInfo, (InteropBitmap)bitmapInfo.InteropBitmap, bitmap => popupImage.Source = bitmap); } else { bitmapInfo.InteropBitmap = SetBitmapHelper(bitmapInfo, (InteropBitmap)bitmapInfo.InteropBitmap, bitmap => image.Source = bitmap); } } }
public static Bitmap Render(IntPtr page, int pixWidth, int pixHeight) { Bitmap bitmap = new Bitmap(pixWidth, pixHeight, PixelFormat.Format32bppArgb); BitmapData bi = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat); PixelFormatEnum pf = ConvertPixelFormat_SystemToLibPdfium(bi.PixelFormat); try { unsafe { BitmapInfo info = new BitmapInfo(); info.Height = bitmap.Height; info.Width = bitmap.Width; info.PixelFormat = pf; info.Data = bi.Scan0; info.Stride = bi.Stride; Pdfium.RenderPageToBitmap(page, &info); } } finally { bitmap.UnlockBits(bi); } return bitmap; }