public static void RenderRaster(SKCanvas canvas, SKBitmap bitmap, SKRect rect, float opacity = 1f) { // Better for quality. Helps to compare to WPF var color = new SKColor(255, 255, 255, (byte)(255 * opacity)); var paint = new SKPaint { Color = color, FilterQuality = SKFilterQuality.High }; canvas.DrawBitmap(bitmap, rect, paint); // Better for performance: canvas.DrawBitmap(bitmap, rect); }
public void InsertImageFromByteArray() { //ExStart //ExFor:DocumentBuilder.InsertImage(Byte[]) //ExSummary:Shows how to import an image into a document from a byte array. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); #if NETSTANDARD2_0 || __MOBILE__ using (SkiaSharp.SKBitmap bitmap = SkiaSharp.SKBitmap.Decode(ImageDir + "Aspose.Words.gif")) { using (SkiaSharp.SKFileWStream fs = new SkiaSharp.SKFileWStream(MyDir + "Artifacts/InsertImageFromByteArray.png")) { bitmap.Encode(fs, SKEncodedImageFormat.Png, 100); } builder.InsertImage(bitmap); builder.Document.Save(MyDir + "Artifacts/Image.CreateFromByteArrayDefault.docx"); } #else // Prepare a byte array of an image. Image image = Image.FromFile(ImageDir + "Aspose.Words.gif"); using (MemoryStream imageBytes = new MemoryStream()) { image.Save(imageBytes, ImageFormat.Png); builder.InsertImage(imageBytes.ToArray()); builder.Document.Save(MyDir + @"\Artifacts\Image.CreateFromByteArrayDefault.doc"); } #endif //ExEnd }
public void InsertImageFromByteArrayCustomSize() { //ExStart //ExFor:DocumentBuilder.InsertImage(Byte[], Double, Double) //ExSummary:Shows how to import an image into a document from a byte array, with a custom size. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); #if NETSTANDARD2_0 || __MOBILE__ using (SkiaSharp.SKBitmap bitmap = SkiaSharp.SKBitmap.Decode(ImageDir + "Aspose.Words.gif")) { using (SkiaSharp.SKFileWStream fs = new SkiaSharp.SKFileWStream(MyDir + "Artifacts/InsertImageFromByteArrayCustomSize.png")) { bitmap.PeekPixels().Encode(fs, SKEncodedImageFormat.Png, 100); } builder.InsertImage(bitmap, ConvertUtil.PixelToPoint(250), ConvertUtil.PixelToPoint(144)); builder.Document.Save(MyDir + "Artifacts/Image.CreateFromByteArrayCustomSize.doc"); } #else // Prepare a byte array of an image. using (Image image = Image.FromFile(ImageDir + "Aspose.Words.gif")) { using (MemoryStream imageBytes = new MemoryStream()) { image.Save(imageBytes, ImageFormat.Png); builder.InsertImage(imageBytes, ConvertUtil.PixelToPoint(250), ConvertUtil.PixelToPoint(144)); builder.Document.Save(MyDir + @"\Artifacts\Image.CreateFromByteArrayCustomSize.doc"); } } #endif //ExEnd }
public void Save(string filename, SkiaSharp.SKEncodedImageFormat format) { if (Disposed) { return; } SkiaSharp.SKBitmap bitmap = new SkiaSharp.SKBitmap(this.Width, this.Height, false); int w = Width; int h = Height; var colorPtr = this.GetColors(); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { var col = *(colorPtr + x + (h - 1 - y) * h); bitmap.SetPixel(x, y, new SkiaSharp.SKColor(col.R, col.G, col.B, col.A)); } } var img = SkiaSharp.SKImage.FromBitmap(bitmap); var data = img.Encode(format, 100); System.IO.File.WriteAllBytes(filename, data.ToArray()); img.Dispose(); bitmap.Dispose(); }
public static SKImage FromBitmap(SKBitmap bitmap) { if (bitmap == null) throw new ArgumentNullException (nameof (bitmap)); var handle = SkiaApi.sk_image_new_from_bitmap (bitmap.Handle); return GetObject<SKImage> (handle); }
public static Image LoadImage(byte[] pb) { if (pb == null) { throw new ArgumentNullException("pb"); } #if !KeePassLibSD // First try to load the data as ICO and afterwards as // normal image, because trying to load an ICO using // the normal image loading methods can result in a // low resolution image try { Image imgIco = ExtractBestImageFromIco(pb); if (imgIco != null) { return(imgIco); } } catch (Exception) { Debug.Assert(false); } #endif MemoryStream ms = new MemoryStream(pb, false); try { return(LoadImagePriv(ms)); } finally { ms.Close(); } }
public static void RenderTexture(SKCanvas canvas, SKBitmap bitmap, float x, float y, float orientation = 0, float offsetX = 0, float offsetY = 0, LabelStyle.HorizontalAlignmentEnum horizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center, LabelStyle.VerticalAlignmentEnum verticalAlignment = LabelStyle.VerticalAlignmentEnum.Center, float opacity = 1f, float scale = 1f) { canvas.Save(); canvas.Translate(x, y); canvas.RotateDegrees(orientation, 0, 0); // todo: or degrees? canvas.Scale(scale, scale); x = offsetX + DetermineHorizontalAlignmentCorrection(horizontalAlignment, bitmap.Width); y = -offsetY + DetermineVerticalAlignmentCorrection(verticalAlignment, bitmap.Height); var halfWidth = bitmap.Width/2; var halfHeight = bitmap.Height/2; var rect = new SKRect(x - halfWidth, y - halfHeight, x + halfWidth, y + halfHeight); RenderTexture(canvas, bitmap, rect, opacity); canvas.Restore(); }
public SKCanvas(SKBitmap bitmap) : this(IntPtr.Zero, true) { if (bitmap == null) throw new ArgumentNullException (nameof (bitmap)); Handle = SkiaApi.sk_canvas_new_from_bitmap (bitmap.Handle); }
private void FixSize() { int width, height; GetPlatformWindowSize(out width, out height); if (Width == width && Height == height) return; Width = width; Height = height; if (Surface != null) { Surface.Dispose(); } if (_bitmap != null) { _bitmap.Dispose(); } _bitmap = new SKBitmap(width, height, SKImageInfo.PlatformColorType, SKAlphaType.Premul); IntPtr length; var pixels = _bitmap.GetPixels(out length); // Wrap the bitmap in a Surface and keep it cached Surface = SKSurface.Create(_bitmap.Info, pixels, _bitmap.RowBytes); }
public void InsertImageFromByteArrayRelativePosition() { //ExStart //ExFor:DocumentBuilder.InsertImage(Byte[], RelativeHorizontalPosition, Double, RelativeVerticalPosition, Double, Double, Double, WrapType) //ExSummary:Shows how to import an image into a document from a byte array, also using relative positions. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); #if NETSTANDARD2_0 || __MOBILE__ using (SkiaSharp.SKBitmap bitmap = SkiaSharp.SKBitmap.Decode(ImageDir + "Aspose.Words.gif")) { using (SkiaSharp.SKFileWStream fs = new SkiaSharp.SKFileWStream(MyDir + "Artifacts/InsertImageFromByteArrayCustomSize.png")) { bitmap.Encode(fs, SKEncodedImageFormat.Png, 100); } builder.InsertImage(bitmap, RelativeHorizontalPosition.Margin, 100, RelativeVerticalPosition.Margin, 100, 200, 100, WrapType.Square); builder.Document.Save(MyDir + "Artifacts/Image.CreateFromByteArrayCustomSize.doc"); } #else // Prepare a byte array of an image. Image image = Image.FromFile(ImageDir + "Aspose.Words.gif"); using (MemoryStream imageBytes = new MemoryStream()) { image.Save(imageBytes, ImageFormat.Png); builder.InsertImage(imageBytes, RelativeHorizontalPosition.Margin, 100, RelativeVerticalPosition.Margin, 100, 200, 100, WrapType.Square); builder.Document.Save(MyDir + @"\Artifacts\Image.CreateFromByteArrayRelativePosition.doc"); } #endif //ExEnd }
/// <summary> /// Resize an image. /// </summary> /// <param name="img">Image to resize.</param> /// <param name="w">Width of the returned image.</param> /// <param name="h">Height of the returned image.</param> /// <param name="f">Flags to customize scaling behavior.</param> /// <returns>Resized image. This object is always different /// from <paramref name="img" /> (i.e. they can be /// disposed separately).</returns> public static Image ScaleImage(Image img, int w, int h, ScaleTransformFlags f) { if (img == null) { throw new ArgumentNullException("img"); } if (w < 0) { throw new ArgumentOutOfRangeException("w"); } if (h < 0) { throw new ArgumentOutOfRangeException("h"); } bool bUIIcon = ((f & ScaleTransformFlags.UIIcon) != ScaleTransformFlags.None); // We must return a Bitmap object for UIUtil.CreateScaledImage Bitmap bmp = new Bitmap(w, h, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(bmp)) { g.Clear(Color.Transparent); g.SmoothingMode = SmoothingMode.HighQuality; g.CompositingQuality = CompositingQuality.HighQuality; int wSrc = img.Width; int hSrc = img.Height; InterpolationMode im = InterpolationMode.HighQualityBicubic; if ((wSrc > 0) && (hSrc > 0)) { if (bUIIcon && ((w % wSrc) == 0) && ((h % hSrc) == 0)) { im = InterpolationMode.NearestNeighbor; } // else if((w < wSrc) && (h < hSrc)) // im = InterpolationMode.HighQualityBilinear; } else { Debug.Assert(false); } g.InterpolationMode = im; RectangleF rSource = new RectangleF(0.0f, 0.0f, wSrc, hSrc); RectangleF rDest = new RectangleF(0.0f, 0.0f, w, h); AdjustScaleRects(ref rSource, ref rDest); g.DrawImage(img, rDest, rSource, GraphicsUnit.Pixel); } return(bmp); }
public static Image ScaleImage(Image img, int w, int h) { if (img == null) { return(null); } return(img.Resize(new SKImageInfo(w, h), SKFilterQuality.High)); }
IBitmapImpl LoadBitmap(byte[] data) { var bitmap = new SKBitmap(); if (!SKImageDecoder.DecodeMemory(data, bitmap)) { throw new ArgumentException("Unable to load bitmap from provided data"); } return new BitmapImpl(bitmap); }
public static Image LoadImage(byte[] pb) { if (pb == null) { throw new ArgumentNullException("pb"); } MemoryStream ms = new MemoryStream(pb, false); try { return(Image.FromStream(ms)); } finally { ms.Close(); } }
public void Setup() { benchmarkDocumentBytes = PixiParser.Serialize(Helper.CreateDocument(Size, Layers)); benchmarkDocument = Helper.CreateDocument(Size, Layers); bitmaps = new SkiaSharp.SKBitmap[Layers]; for (int i = 0; i < Layers; i++) { bitmaps[i] = Helper.CreateSKBitmap(Size); } }
public static Image LoadImage(byte[] pb) { if (pb == null) { return(null); } using (var ms = new MemoryStream(pb, false)) { return(Image.Decode(ms)); } }
internal static ulong HashImage64(Image img) { Bitmap bmp = (img as Bitmap); if (bmp == null) { Debug.Assert(false); return(0); } BitmapData bd = null; try { int w = bmp.Width, h = bmp.Height; if ((w <= 0) || (h <= 0)) { Debug.Assert(false); return(0); } bd = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); if (bd.Stride != (w * 4)) { Debug.Assert(false); return(0); } Debug.Assert(Marshal.SizeOf(typeof(int)) == 4); int cp = w * h; int[] v = new int[cp]; Marshal.Copy(bd.Scan0, v, 0, cp); ulong u = (ulong)w * 0x50EF39EB5BE34CA9; for (int i = 0; i < cp; ++i) { u = (u ^ (uint)v[i]) * 0x6E18585D2D174BD5; } return(u ^ (u >> 32)); } catch (Exception) { Debug.Assert(false); } finally { if (bd != null) { bmp.UnlockBits(bd); } } return(0); }
public static void SaveImage(Image img, string path) { if (img == null || path == null) { return; } SKImage image = SKImage.FromBitmap(img); SKData png = image.Encode(SKEncodedImageFormat.Png, 100); using (var filestream = File.OpenWrite(path)) { png.SaveTo(filestream); } }
internal static string ImageToDataUri(Image img) { if (img == null) { Debug.Assert(false); return(string.Empty); } byte[] pb = null; using (MemoryStream ms = new MemoryStream()) { img.Save(ms, ImageFormat.Png); pb = ms.ToArray(); } return(StrUtil.DataToDataUri(pb, "image/png")); }
private static Image LoadImagePriv(Stream s) { // Image.FromStream wants the stream to be open during // the whole lifetime of the image; as we can't guarantee // this, we make a copy of the image Image imgSrc = null; try { #if !KeePassLibSD imgSrc = Image.FromStream(s); Bitmap bmp = new Bitmap(imgSrc.Width, imgSrc.Height, PixelFormat.Format32bppArgb); try { bmp.SetResolution(imgSrc.HorizontalResolution, imgSrc.VerticalResolution); Debug.Assert(bmp.Size == imgSrc.Size); } catch (Exception) { Debug.Assert(false); } #else imgSrc = new Bitmap(s); Bitmap bmp = new Bitmap(imgSrc.Width, imgSrc.Height); #endif using (Graphics g = Graphics.FromImage(bmp)) { g.Clear(Color.Transparent); #if !KeePassLibSD g.DrawImageUnscaled(imgSrc, 0, 0); #else g.DrawImage(imgSrc, 0, 0); #endif } return(bmp); } finally { if (imgSrc != null) { imgSrc.Dispose(); } } }
private Response RenderMap(dynamic parameters) { var gameServer = this.servers.OfType <IGameServer>().FirstOrDefault(s => s.Id == (byte)parameters.serverId); var map = gameServer?.ServerInfo.Maps.FirstOrDefault(m => m.MapNumber == (short)parameters.mapId); if (map == null) { Log.Warn($"requested map not available. map number: {parameters.mapId}; server id: {parameters.serverId}"); return(null); } var terrain = new GameMapTerrain(map.MapName, map.TerrainData); using (var bitmap = new SkiaSharp.SKBitmap(0x100, 0x100)) { for (int y = 0; y < 0x100; y++) { for (int x = 0; x < 0x100; x++) { var color = SKColors.Black; if (terrain.SafezoneMap[y, x]) { color = SKColors.Gray; } else if (terrain.WalkMap[y, x]) { color = SKColors.SpringGreen; } bitmap.SetPixel(x, y, color); } } using (var memoryStream = new SKDynamicMemoryWStream()) { if (SKPixmap.Encode(memoryStream, bitmap, SKEncodedImageFormat.Png, 100)) { return(this.Response.FromStream(memoryStream.DetachAsData().AsStream, "image/png")); } } return(null); } }
private static SKBitmap CreateLabelAsBitmap(LabelStyle style, string text, SKPaint paint) { var rect = new SKRect(); paint.MeasureText(text, ref rect); var backRect = new SKRect(0, 0, rect.Width + 6, rect.Height + 6); var bitmap = new SKBitmap((int)backRect.Width, (int)backRect.Height); using (var target = new SKCanvas(bitmap)) { target.Clear(); DrawBackground(style, backRect, target); target.DrawText(text, -rect.Left + 3, -rect.Top +3, paint); return bitmap; } }
public async Task<Tuple<Stream, LoadingResult, ImageInformation>> Resolve(string identifier, TaskParameter parameters, CancellationToken token) { ImageSource source = parameters.Source; if (parameters.LoadingPlaceholderPath == identifier) source = parameters.LoadingPlaceholderSource; else if (parameters.ErrorPlaceholderPath == identifier) source = parameters.ErrorPlaceholderSource; var resolvedData = await Configuration.DataResolverFactory .GetResolver(identifier, source, parameters, Configuration) .Resolve(identifier, parameters, token); if (resolvedData?.Item1 == null) throw new FileNotFoundException(identifier); var svg = new SKSvg() { ThrowOnUnsupportedElement = false, }; SKPicture picture; using (var svgStream = resolvedData.Item1) { picture = svg.Load(resolvedData?.Item1); } using (var bitmap = new SKBitmap(200, 200, true)) using (var canvas = new SKCanvas(bitmap)) { float canvasMin = Math.Min(200, 200); float svgMax = Math.Max(svg.Picture.Bounds.Width, svg.Picture.Bounds.Height); float scale = canvasMin / svgMax; var matrix = SKMatrix.MakeScale(scale, scale); canvas.DrawPicture(picture, ref matrix); using (var image = SKImage.FromBitmap(bitmap)) { var stream = image.Encode()?.AsStream(); return new Tuple<Stream, LoadingResult, ImageInformation>(stream, resolvedData.Item2, resolvedData.Item3); } } }
void CreateGraphicsFromNativeHdc(int width, int height) { skBitmap = new SKBitmap(width, height); skCanvas = new SKCanvas(skBitmap); // stroke = new SKPaint(); stroke.IsStroke = true; // fill = new SKPaint(); fill.IsStroke = false; // textFill = new SKPaint(); textFill.IsAntialias = true; //--------------------------------------- //--------------------------------------- this.CurrentFont = new RequestFont("tahoma", 14); this.CurrentTextColor = Color.Black; //--------------------------------------- }
// ExStart:RenderShapeToGraphics public static string RenderShapeToGraphics(string dataDir, Shape shape) { ShapeRenderer r = shape.GetShapeRenderer(); // Find the size that the shape will be rendered to at the specified scale and resolution. Size shapeSizeInPixels = r.GetSizeInPixels(1.0f, 96.0f); // Rotating the shape may result in clipping as the image canvas is too small. Find the longest side // And make sure that the graphics canvas is large enough to compensate for this. int maxSide = System.Math.Max(shapeSizeInPixels.Width, shapeSizeInPixels.Height); using (SkiaSharp.SKBitmap bitmap = new SkiaSharp.SKBitmap((int)(maxSide * 1.25), (int)(maxSide * 1.25))) { // Rendering to a graphics object means we can specify settings and transformations to be applied to // The shape that is rendered. In our case we will rotate the rendered shape. using (SkiaSharp.SKCanvas gr = new SkiaSharp.SKCanvas(bitmap)) { // Clear the shape with the background color of the document. gr.DrawColor(new SkiaSharp.SKColor(shape.Document.PageColor.R, shape.Document.PageColor.G, shape.Document.PageColor.B, shape.Document.PageColor.A)); // Center the rotation using translation method below gr.Translate((float)bitmap.Width / 8, (float)bitmap.Height / 2); // Rotate the image by 45 degrees. gr.RotateDegrees(45); // Undo the translation. gr.Translate(-(float)bitmap.Width / 8, -(float)bitmap.Height / 2); // Render the shape onto the graphics object. r.RenderToSize(gr, 0, 0, shapeSizeInPixels.Width, shapeSizeInPixels.Height); } // Save output to file. using (System.IO.FileStream fs = System.IO.File.Create(dataDir + "/RenderToSize_Out.png")) { SKData d = SKImage.FromBitmap(bitmap).Encode(SKEncodedImageFormat.Png, 100); d.SaveTo(fs); } } return("\nShape rendered to graphics successfully.\nFile saved at " + dataDir); }
public BitmapHelper(string path) { Bitmap bitmap; try { bitmap = Bitmap.Decode(File.OpenRead(path)); } catch (Exception) { bitmap = new Bitmap(10, 10); for (int i = 0; i < 10; i++) { for (int w = 0; w < 10; w++) { bitmap.SetPixel(i, w, SKColors.White); } } } IntPtr ptr = bitmap.GetPixels(); int bytes = Math.Abs(bitmap.RowBytes) * bitmap.Height; byte[] rgbValues = new byte[bytes]; System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); colors = new SKColor[bitmap.Width, bitmap.Height]; for (int counter = 0; counter < rgbValues.Length; counter += 4) { int i_am = counter / 4; colors[i_am % bitmap.Width, i_am / bitmap.Width] = new SKColor( rgbValues[counter + 2], rgbValues[counter + 1], rgbValues[counter + 0], rgbValues[counter + 3]); } bitmap.Dispose(); }
public static Image ScaleTest(Image[] vIcons) { Bitmap bmp = new Bitmap(1024, vIcons.Length * (256 + 12), PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(bmp)) { g.Clear(Color.White); int[] v = new int[] { 16, 24, 32, 48, 64, 128, 256 }; int x; int y = 8; foreach (Image imgIcon in vIcons) { if (imgIcon == null) { Debug.Assert(false); continue; } x = 128; foreach (int q in v) { using (Image img = ScaleImage(imgIcon, q, q, ScaleTransformFlags.UIIcon)) { g.DrawImageUnscaled(img, x, y); } x += q + 8; } y += v[v.Length - 1] + 8; } } return(bmp); }
/// <summary> /// Combines 2 images into one, given the shared ImageStats for both supplied images. /// </summary> /// <param name="info">the ImageStats object used to generate both bottom and top tiles.</param> /// <param name="bottomTile">the tile to use as the base of the image. Expected to be opaque.</param> /// <param name="topTile">The tile to layer on top. Expected to be at least partly transparent or translucent.</param> /// <returns></returns> public byte[] LayerTiles(ImageStats info, byte[] bottomTile, byte[] topTile) { SkiaSharp.SKBitmap bitmap = new SkiaSharp.SKBitmap(info.imageSizeX, info.imageSizeY, SkiaSharp.SKColorType.Rgba8888, SkiaSharp.SKAlphaType.Premul); SkiaSharp.SKCanvas canvas = new SkiaSharp.SKCanvas(bitmap); SkiaSharp.SKPaint paint = new SkiaSharp.SKPaint(); canvas.Scale(1, 1, info.imageSizeX / 2, info.imageSizeY / 2); paint.IsAntialias = true; var baseBmp = SkiaSharp.SKBitmap.Decode(bottomTile); var topBmp = SkiaSharp.SKBitmap.Decode(topTile); canvas.DrawBitmap(baseBmp, 0, 0); canvas.DrawBitmap(topBmp, 0, 0); var ms = new MemoryStream(); var skms = new SkiaSharp.SKManagedWStream(ms); bitmap.Encode(skms, SkiaSharp.SKEncodedImageFormat.Png, 100); var output = ms.ToArray(); skms.Dispose(); ms.Close(); ms.Dispose(); return(output); }
private Stream RenderMap(IGameMapInfo map) { var terrain = new GameMapTerrain(map.MapName, map.TerrainData); using (var bitmap = new SkiaSharp.SKBitmap(0x100, 0x100)) { for (int y = 0; y < 0x100; y++) { for (int x = 0; x < 0x100; x++) { var color = SKColors.Black; if (terrain.SafezoneMap[y, x]) { color = SKColors.Gray; } else if (terrain.WalkMap[y, x]) { color = SKColors.SpringGreen; } else { // we use the default color. } bitmap.SetPixel(x, y, color); } } using (var memoryStream = new SKDynamicMemoryWStream()) { if (SKPixmap.Encode(memoryStream, bitmap, SKEncodedImageFormat.Png, 100)) { return(memoryStream.DetachAsData().AsStream()); } } return(null); } }
public IBitmapImpl LoadBitmap(System.IO.Stream stream) { using (var s = new SKManagedStream(stream)) { using (var codec = SKCodec.Create(s)) { var info = codec.Info; var bitmap = new SKBitmap(info.Width, info.Height, SKImageInfo.PlatformColorType, info.IsOpaque ? SKAlphaType.Opaque : SKAlphaType.Premul); IntPtr length; var result = codec.GetPixels(bitmap.Info, bitmap.GetPixels(out length)); if (result == SKCodecResult.Success || result == SKCodecResult.IncompleteInput) { return new BitmapImpl(bitmap); } else { throw new ArgumentException("Unable to load bitmap from provided data"); } } } }
public void InsertImageFromImageRelativePosition() { //ExStart //ExFor:DocumentBuilder.InsertImage(Image, RelativeHorizontalPosition, Double, RelativeVerticalPosition, Double, Double, Double, WrapType) //ExSummary:Shows how to import an image into a document, also using relative positions. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); #if NETSTANDARD2_0 || __MOBILE__ using (SkiaSharp.SKBitmap rasterImage = SkiaSharp.SKBitmap.Decode(ImageDir + "Aspose.Words.gif")) { builder.InsertImage(rasterImage, RelativeHorizontalPosition.Margin, 100, RelativeVerticalPosition.Margin, 100, 200, 100, WrapType.Square); } #else using (Image rasterImage = Image.FromFile(ImageDir + "Aspose.Words.gif")) { builder.InsertImage(rasterImage, RelativeHorizontalPosition.Margin, 100, RelativeVerticalPosition.Margin, 100, 200, 100, WrapType.Square); } #endif builder.Document.Save(MyDir + @"\Artifacts\Image.CreateFromImageWithStreamRelativePosition.doc"); //ExEnd }
public void InsertImageFromImageCustomSize() { //ExStart //ExFor:DocumentBuilder.InsertImage(Image, Double, Double) //ExSummary:Shows how to import an image into a document, with a custom size. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); #if NETSTANDARD2_0 || __MOBILE__ using (SkiaSharp.SKBitmap rasterImage = SkiaSharp.SKBitmap.Decode(ImageDir + "Aspose.Words.gif")) { builder.InsertImage(rasterImage, ConvertUtil.PixelToPoint(450), ConvertUtil.PixelToPoint(144)); builder.Writeln(); } #else using (Image rasterImage = Image.FromFile(ImageDir + "Aspose.Words.gif")) { builder.InsertImage(rasterImage, ConvertUtil.PixelToPoint(450), ConvertUtil.PixelToPoint(144)); builder.Writeln(); } #endif builder.Document.Save(MyDir + @"\Artifacts\Image.CreateFromImageWithStreamCustomSize.doc"); //ExEnd }
public SKAutoLockPixels (SKBitmap bitmap) : this (bitmap, true) { }
private static Image ExtractBestImageFromIco(byte[] pb) { List <GfxImage> l = UnpackIco(pb); if ((l == null) || (l.Count == 0)) { return(null); } long qMax = 0; foreach (GfxImage gi in l) { if (gi.Width == 0) { gi.Width = 256; } if (gi.Height == 0) { gi.Height = 256; } qMax = Math.Max(qMax, (long)gi.Width * (long)gi.Height); } byte[] pbHdrPng = new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }; byte[] pbHdrJpeg = new byte[] { 0xFF, 0xD8, 0xFF }; Image imgBest = null; int bppBest = -1; foreach (GfxImage gi in l) { if (((long)gi.Width * (long)gi.Height) < qMax) { continue; } byte[] pbImg = gi.Data; Image img = null; try { if ((pbImg.Length > pbHdrPng.Length) && MemUtil.ArraysEqual(pbHdrPng, MemUtil.Mid <byte>(pbImg, 0, pbHdrPng.Length))) { img = GfxUtil.LoadImage(pbImg); } else if ((pbImg.Length > pbHdrJpeg.Length) && MemUtil.ArraysEqual(pbHdrJpeg, MemUtil.Mid <byte>(pbImg, 0, pbHdrJpeg.Length))) { img = GfxUtil.LoadImage(pbImg); } else { using (MemoryStream ms = new MemoryStream(pb, false)) { using (Icon ico = new Icon(ms, gi.Width, gi.Height)) { img = ico.ToBitmap(); } } } } catch (Exception) { Debug.Assert(false); } if (img == null) { continue; } if ((img.Width < gi.Width) || (img.Height < gi.Height)) { Debug.Assert(false); img.Dispose(); continue; } int bpp = GetBitsPerPixel(img.PixelFormat); if (bpp > bppBest) { if (imgBest != null) { imgBest.Dispose(); } imgBest = img; bppBest = bpp; } else { img.Dispose(); } } return(imgBest); }
public static SKBitmap Decode (SKCodec codec, SKImageInfo bitmapInfo) { if (codec == null) { throw new ArgumentNullException (nameof (codec)); } // construct a color table for the decode if necessary SKColorTable colorTable = null; int colorCount = 0; if (bitmapInfo.ColorType == SKColorType.Index8) { colorTable = new SKColorTable (); } // read the pixels and color table var bitmap = new SKBitmap (bitmapInfo, colorTable); IntPtr length; var result = codec.GetPixels (bitmapInfo, bitmap.GetPixels (out length), colorTable, ref colorCount); if (result != SKCodecResult.Success && result != SKCodecResult.IncompleteInput) { bitmap.Dispose (); bitmap = null; } return bitmap; }
public void DrawBitmap(SKBitmap bitmap, float x, float y, SKPaint paint = null) { if (bitmap == null) throw new ArgumentNullException ("bitmap"); SkiaApi.sk_canvas_draw_bitmap (Handle, bitmap.Handle, x, y, paint == null ? IntPtr.Zero : paint.Handle); }
public void DrawBitmapLattice(SKBitmap bitmap, int[] xDivs, int[] yDivs, SKRect dst, SKPaint paint = null) { if (bitmap == null) throw new ArgumentNullException (nameof (bitmap)); if (xDivs == null) throw new ArgumentNullException (nameof (xDivs)); if (yDivs == null) throw new ArgumentNullException (nameof (yDivs)); SkiaApi.sk_canvas_draw_bitmap_lattice (Handle, bitmap.Handle, xDivs, xDivs.Length, yDivs, yDivs.Length, ref dst, paint == null ? IntPtr.Zero : paint.Handle); }
public BitmapImpl(SKBitmap bm) { Bitmap = bm; PixelHeight = bm.Height; PixelWidth = bm.Width; }
public BitmapDrawingContext(SKBitmap bitmap) : this(CreateSurface(bitmap)) { }
public static SKShader CreateBitmap (SKBitmap src, SKShaderTileMode tmx, SKShaderTileMode tmy, SKMatrix localMatrix) { if (src == null) throw new ArgumentNullException (nameof (src)); return GetObject<SKShader> (SkiaApi.sk_shader_new_bitmap (src.Handle, tmx, tmy, ref localMatrix)); }
public unsafe void DrawBitmapLattice (SKBitmap bitmap, SKLattice lattice, SKRect dst, SKPaint paint = null) { if (bitmap == null) throw new ArgumentNullException (nameof (bitmap)); if (lattice.XDivs == null) throw new ArgumentNullException (nameof (lattice.XDivs)); if (lattice.YDivs == null) throw new ArgumentNullException (nameof (lattice.YDivs)); fixed (int* x = lattice.XDivs) fixed (int* y = lattice.YDivs) fixed (SKLatticeFlags* f = lattice.Flags) { var nativeLattice = new SKLatticeInternal { fBounds = null, fFlags = f, fXCount = lattice.XDivs.Length, fXDivs = x, fYCount = lattice.YDivs.Length, fYDivs = y, }; if (lattice.Bounds != null) { var bounds = lattice.Bounds.Value; nativeLattice.fBounds = &bounds; } SkiaApi.sk_canvas_draw_bitmap_lattice (Handle, bitmap.Handle, ref nativeLattice, ref dst, paint == null ? IntPtr.Zero : paint.Handle); } }
public void DrawBitmapLattice (SKBitmap bitmap, int[] xDivs, int[] yDivs, SKRect dst, SKPaint paint = null) { var lattice = new SKLattice { Bounds = null, Flags = null, XDivs = xDivs, YDivs = yDivs }; DrawBitmapLattice (bitmap, lattice, dst, paint); }
public override void DrawImage(ActualImage actualImage, double x, double y) { //create Gdi bitmap from actual image int w = actualImage.Width; int h = actualImage.Height; switch (actualImage.PixelFormat) { case Agg.PixelFormat.ARGB32: { using (SKBitmap newBmp = new SKBitmap(actualImage.Width, actualImage.Height)) { newBmp.LockPixels(); byte[] actualImgBuffer = ActualImage.GetBuffer(actualImage); System.Runtime.InteropServices.Marshal.Copy( actualImgBuffer, 0, newBmp.GetPixels(), actualImgBuffer.Length); newBmp.UnlockPixels(); } //newBmp.internalBmp.LockPixels(); //byte[] actualImgBuffer = ActualImage.GetBuffer(actualImage); //System.Runtime.InteropServices.Marshal.Copy( // actualImgBuffer, // 0, // newBmp.internalBmp.GetPixels(), // actualImgBuffer.Length); //newBmp.internalBmp.UnlockPixels(); //return newBmp; //copy data from acutal buffer to internal representation bitmap //using (MySkBmp bmp = MySkBmp.CopyFrom(actualImage)) //{ // _skCanvas.DrawBitmap(bmp.internalBmp, (float)x, (float)y); //} } break; case Agg.PixelFormat.RGB24: { } break; case Agg.PixelFormat.GrayScale8: { } break; default: throw new NotSupportedException(); } }
public static void RenderTexture(SKCanvas canvas, SKBitmap bitmap, SKRect rect, float opacity = 1f) { var color = new SKColor(255, 255, 255, (byte) (255*opacity)); var paint = new SKPaint {Color = color, FilterQuality = SKFilterQuality.High}; canvas.DrawBitmap(bitmap, rect, paint); }
public bool Resize(SKBitmap dst, SKBitmapResizeMethod method) { return(Resize(dst, this, method)); }
public static Image ScaleImage(Image img, int w, int h) { return(ScaleImage(img, w, h, ScaleTransformFlags.None)); }
public SKAutoLockPixels (SKBitmap bitmap, bool doLock) { this.bitmap = bitmap; this.doLock = doLock; if (bitmap != null && doLock) { bitmap.LockPixels (); } }
public static SKShader CreateBitmap(SKBitmap src, SKShaderTileMode tmx, SKShaderTileMode tmy, SKMatrix localMatrix) { return(GetObject <SKShader> (SkiaApi.sk_shader_new_bitmap(src.Handle, tmx, tmy, ref localMatrix))); }
/// <summary> /// Perform the unlock now, instead of waiting for the Dispose. /// Will only do this once. /// </summary> public void Unlock () { if (bitmap != null && doLock) { bitmap.UnlockPixels (); bitmap = null; } }
public bool CopyTo(SKBitmap destination, SKColorType colorType) { return(SkiaApi.sk_bitmap_copy(Handle, destination.Handle, colorType)); }
public BitmapImpl(int width, int height) { PixelHeight = height; PixelWidth = width; Bitmap = new SKBitmap(width, height, SKColorType.N_32, SKAlphaType.Premul); }
public static SKShader CreateBitmap(SKBitmap src, SKShaderTileMode tmx, SKShaderTileMode tmy) { return(GetObject <SKShader> (SkiaApi.sk_shader_new_bitmap(src.Handle, tmx, tmy, IntPtr.Zero))); }
private static SKSurface CreateSurface(SKBitmap bitmap) { IntPtr length; return SKSurface.Create(bitmap.Info, bitmap.GetPixels(out length), bitmap.RowBytes); }
public SKBitmap Copy (SKColorType colorType) { var destination = new SKBitmap (); if (!SkiaApi.sk_bitmap_copy (Handle, destination.Handle, colorType)) { destination.Dispose (); destination = null; } return destination; }
public void DrawBitmap(SKBitmap bitmap, SKRect source, SKRect dest, SKPaint paint = null) { if (bitmap == null) throw new ArgumentNullException ("bitmap"); SkiaApi.sk_canvas_draw_bitmap_rect (Handle, bitmap.Handle, ref source, ref dest, paint == null ? IntPtr.Zero : paint.Handle); }
public bool CopyTo (SKBitmap destination, SKColorType colorType) { if (destination == null) { throw new ArgumentNullException (nameof (destination)); } return SkiaApi.sk_bitmap_copy (Handle, destination.Handle, colorType); }
public void DrawBitmapNinePatch(SKBitmap bitmap, SKRectI center, SKRect dst, SKPaint paint = null) { if (bitmap == null) throw new ArgumentNullException (nameof (bitmap)); // the "center" rect must fit inside the bitmap "rect" if (!SKRect.Create (bitmap.Info.Size).Contains (center)) throw new ArgumentOutOfRangeException (nameof (center)); var xDivs = new [] { center.Left, center.Right }; var yDivs = new [] { center.Top, center.Bottom }; DrawBitmapLattice (bitmap, xDivs, yDivs, dst, paint); }
private void Swap(SKBitmap other) { SkiaApi.sk_bitmap_swap(Handle, other.Handle); }
} // End Function LoadImage private void DrawImage() { int bitness = System.IntPtr.Size * 8; System.Console.WriteLine(bitness); // https://developer.xamarin.com/guides/cross-platform/drawing/introduction/ // https://developer.xamarin.com/api/type/SkiaSharp.SKSurface/ // https://forums.xamarin.com/discussion/77883/skiasharp-graphics-basics // Make sure the Microsoft Visual C++ 2015 Redistributable is installed if this error occurs: // Unable to load DLL 'libSkiaSharp.dll': The specified module could not be found. using (SKSurface surface = SKSurface.Create(width: 640, height: 480, colorType: SKColorType.Bgra8888, alphaType: SKAlphaType.Premul)) { SKCanvas canvas = surface.Canvas; canvas.Clear(SKColors.Transparent); using (SKPaint paint = new SKPaint()) { // paint.ImageFilter = SKImageFilter.CreateBlur(5, 5); // Dispose ! paint.IsAntialias = true; // paint.Color = new SKColor(0xff, 0x00, 0xff); paint.Color = new SKColor(0x2c, 0x3e, 0x50); paint.StrokeCap = SKStrokeCap.Round; paint.Typeface = SkiaSharp.SKTypeface.FromFamilyName("Impact", SKTypefaceStyle.Bold); paint.TextSize = 12; canvas.DrawText("foobar", 10, 10, paint); // SkiaSharp.SKRect rect = new SkiaSharp.SKRect(); SkiaSharp.SKRect rect = MeasureText("foobar", "Impact", 12, SKTypefaceStyle.Bold); // paint.MeasureText("foobar", ref rect); System.Console.WriteLine(rect); SKRect textOverlayRectangle = new SKRect(); textOverlayRectangle.Left = 9; // x textOverlayRectangle.Top = 10 - rect.Height; // y textOverlayRectangle.Right = textOverlayRectangle.Left + rect.Width; textOverlayRectangle.Bottom = textOverlayRectangle.Top + rect.Height; // canvas.DrawRect(textOverlayRectangle, paint); // https://chromium.googlesource.com/external/skia/+/master/experimental/SkiaExamples/HelloSkiaExample.cpp SkiaSharp.SKPoint[] linearPoints = new SkiaSharp.SKPoint[] { new SkiaSharp.SKPoint(0, 0), new SkiaSharp.SKPoint(300, 300) }; SkiaSharp.SKColor[] linearColors = new SkiaSharp.SKColor[] { SkiaSharp.SKColors.Green, SkiaSharp.SKColors.Black }; // canvas.Restore(); // canvas.Translate(100, 200); // canvas.RotateDegrees(45); // SKShader shader = SkiaSharp.SKShader.CreateLinearGradient(linearPoints[0], linearPoints[1], linearColors, new float[] { 1.0f, 2000.0f }, SKShaderTileMode.Repeat); // paint.Shader = shader; SkiaSharp.SKBitmap shaderPattern = LoadImage(MapProjectPath(@"~mytile.png")); SKShader hatchShader = SkiaSharp.SKShader.CreateBitmap(shaderPattern, SKShaderTileMode.Mirror, SKShaderTileMode.Repeat); paint.Shader = hatchShader; // create the Xamagon path using (SKPath path = new SKPath()) { path.MoveTo(71.4311121f, 56f); path.CubicTo(68.6763107f, 56.0058575f, 65.9796704f, 57.5737917f, 64.5928855f, 59.965729f); path.LineTo(43.0238921f, 97.5342563f); path.CubicTo(41.6587026f, 99.9325978f, 41.6587026f, 103.067402f, 43.0238921f, 105.465744f); path.LineTo(64.5928855f, 143.034271f); path.CubicTo(65.9798162f, 145.426228f, 68.6763107f, 146.994582f, 71.4311121f, 147f); path.LineTo(114.568946f, 147f); path.CubicTo(117.323748f, 146.994143f, 120.020241f, 145.426228f, 121.407172f, 143.034271f); path.LineTo(142.976161f, 105.465744f); path.CubicTo(144.34135f, 103.067402f, 144.341209f, 99.9325978f, 142.976161f, 97.5342563f); path.LineTo(121.407172f, 59.965729f); path.CubicTo(120.020241f, 57.5737917f, 117.323748f, 56.0054182f, 114.568946f, 56f); path.LineTo(71.4311121f, 56f); path.Close(); // draw the Xamagon path canvas.DrawPath(path, paint); } // End Using path // ClipDeviceBounds not ClipBounds canvas.DrawLine(0, 0, canvas.ClipDeviceBounds.Width, canvas.ClipDeviceBounds.Height, paint); canvas.DrawLine(0, canvas.ClipDeviceBounds.Height, canvas.ClipDeviceBounds.Width, 0, paint); canvas.DrawLine(0 + 1, 0, 0 + 1, canvas.ClipDeviceBounds.Height, paint); canvas.DrawLine(0, surface.Canvas.ClipDeviceBounds.Height / 2, canvas.ClipDeviceBounds.Width, canvas.ClipDeviceBounds.Height / 2, paint); canvas.DrawLine(canvas.ClipDeviceBounds.Width - 1, 0 + 1, canvas.ClipDeviceBounds.Width - 1, canvas.ClipDeviceBounds.Height, paint); } // End Using paint // Your drawing code goes here. // surface.Snapshot().Encode(SKImageEncodeFormat.Webp, 80); // SKData p = surface.Snapshot().Encode(); SKData p = surface.Snapshot().Encode(SKImageEncodeFormat.Png, 80); // p.SaveTo() using (System.IO.MemoryStream ms = new System.IO.MemoryStream(p.ToArray())) { this.pictureBox1.Image = System.Drawing.Image.FromStream(ms); } // End Using ms System.IO.File.WriteAllBytes(MapProjectPath("~testme.png"), p.ToArray()); } // End Using surface // this.Close(); } // End Sub
public BitmapImpl(int width, int height) { PixelHeight = height; PixelWidth = width; Bitmap = new SKBitmap(width, height, SKImageInfo.PlatformColorType, SKAlphaType.Premul); }