public static Pixbuf ToPixbuf(this SKPixmap pixmap) { using (var image = SKImage.FromPixels(pixmap)) { return(image.ToPixbuf()); } }
public void ReleaseImagePixelsWasInvoked() { bool released = false; var onRelease = new SKImageRasterReleaseDelegate((addr, ctx) => { Marshal.FreeCoTaskMem(addr); released = true; Assert.Equal("RELEASING!", ctx); }); var info = new SKImageInfo(1, 1); var pixels = Marshal.AllocCoTaskMem(info.BytesSize); using (var pixmap = new SKPixmap(info, pixels)) using (var image = SKImage.FromPixels(pixmap, onRelease, "RELEASING!")) { Assert.False(image.IsTextureBacked); using (var raster = image.ToRasterImage()) { Assert.Equal(image, raster); } Assert.False(released, "The SKImageRasterReleaseDelegate was called too soon."); } Assert.True(released, "The SKImageRasterReleaseDelegate was not called."); }
public static byte[] GenerateCodePng(string Text, int Width, int Height) { BarcodeWriterPixelData Writer = new BarcodeWriterPixelData() { Format = BarcodeFormat.QR_CODE, Options = new QrCodeEncodingOptions() { Width = Width, Height = Height } }; PixelData QrCode = Writer.Write(Text); Width = QrCode.Width; Height = QrCode.Height; int Size = Width * Height << 2; using (SKData Data = SKData.Create(Size)) { Marshal.Copy(QrCode.Pixels, 0, Data.Data, Size); using (SKImage Result = SKImage.FromPixels(new SKImageInfo(Width, Height, SKColorType.Bgra8888), Data, Width << 2)) { using (SKData Encoded = Result.Encode(SKEncodedImageFormat.Png, 100)) { return(Encoded.ToArray()); } } } }
public static System.Drawing.Bitmap ToBitmap(this SKPixmap pixmap) { using (var image = SKImage.FromPixels(pixmap)) { return(image.ToBitmap()); } }
public void Draw(SKCanvas canvas) { var info = this.info; // if there are no pixels, clean up and return if (info.Width == 0 || info.Height == 0) { return; } // if the memory size has changed, then reset the underlying memory if (bitmap != null && (bitmap.Handle == IntPtr.Zero || bitmap.Width != info.Width || bitmap?.Height != info.Height)) { FreeBitmap(); } if (bitmap == null) { bitmap = Bitmap.CreateBitmap(info.Width, info.Height, Bitmap.Config.Argb8888); bitmapCanvas = new Canvas(bitmap); } bitmap.EraseColor(Android.Graphics.Color.Transparent); base.Draw(bitmapCanvas); using (var image = SKImage.FromPixels(info, bitmap.LockPixels(), info.RowBytes)) { canvas.DrawImage(image, SKPoint.Empty); bitmap.UnlockPixels(); } }
public static Task <SKImage?> ToSKImageAsync(this ImageSource imageSource, CancellationToken cancellationToken = default) { if (imageSource == null) { throw new ArgumentNullException(nameof(imageSource)); } return(imageSource switch { // 1. first try SkiaSharp sources SKImageImageSource iis => FromSkia(iis.Image), SKBitmapImageSource bis => FromSkia(SKImage.FromBitmap(bis.Bitmap)), SKPixmapImageSource xis => FromSkia(SKImage.FromPixels(xis.Pixmap)), SKPictureImageSource pis => FromSkia(SKImage.FromPicture(pis.Picture, pis.Dimensions)), // 2. then try Stream sources StreamImageSource stream => FromStream(stream.Stream.Invoke(cancellationToken)), UriImageSource uri => FromStream(uri.GetStreamAsync(cancellationToken)), // 3. finally, use the handlers FileImageSource file => FromHandler(PlatformToSKImageAsync(file, cancellationToken)), FontImageSource font => FromHandler(PlatformToSKImageAsync(font, cancellationToken)), // 4. all is lost _ => throw new ArgumentException("Unable to determine the type of image source.", nameof(imageSource)) });
public void DrawImage([NotNull] byte[] textureData, SurfaceFormat textureFormat, int textureWidth, int textureHeight, float x, float y, float width, float height, bool antialiased = true) { if (_canvas == null) { return; } Debug.Assert(textureFormat == SurfaceFormat.Color); using (var paint = new SKPaint()) { paint.IsAntialias = antialiased; paint.HintingLevel = SKPaintHinting.Full; paint.IsAutohinted = true; var imageInfo = new SKImageInfo(textureWidth, textureHeight, SKColorType.Rgba8888, SKAlphaType.Premul); unsafe { fixed(byte *bufferPtr = textureData) { var ptr = new IntPtr(bufferPtr); using (var image = SKImage.FromPixels(imageInfo, ptr, textureWidth * sizeof(int))) { var destRect = new SKRect(x, y, x + width, y + height); _canvas.DrawImage(image, destRect, paint); } } } } }
public Stream GetBitmap(double nHour, double nMinute, double nSecond, int width = 512, int height = 512, bool bDrawBackImage = false) { if (bitmap == null || bitmap.Width != width || bitmap.Height != height) { bitmap?.Dispose(); bitmap = new SKBitmap(width, height); } SKCanvas canvas = new SKCanvas(bitmap); DrawCanvas(canvas, nHour, nMinute, nSecond, width, height, bDrawBackImage); // create an image COPY //SKImage image = SKImage.FromBitmap(bitmap); // OR // create an image WRAPPER SKImage image = SKImage.FromPixels(bitmap.PeekPixels()); // encode the image (defaults to PNG) SKData encoded = image.Encode(); // get a stream over the encoded data Stream stream = encoded.AsStream(); return(stream); }
public static WriteableBitmap ToWriteableBitmap(this SKPixmap pixmap) { using (var image = SKImage.FromPixels(pixmap)) { return(image.ToWriteableBitmap()); } }
public static System.Drawing.Bitmap ToBitmap(this SKBitmap skiaBitmap) { using (var image = SKImage.FromPixels(skiaBitmap.PeekPixels())) { return(image.ToBitmap()); } }
/// <summary> /// Creates a bitmap of the graph. /// </summary> /// <param name="Settings">Graph settings.</param> /// <param name="States">State object(s) that contain graph-specific information about its inner states. /// These can be used in calls back to the graph object to make actions on the generated graph.</param> /// <returns>Bitmap</returns> public override SKImage CreateBitmap(GraphSettings Settings, out object[] States) { SKImageInfo ImageInfo = new SKImageInfo(this.bitmap.Width, this.bitmap.Height, SKColorType.Bgra8888); int c = ImageInfo.BytesSize; States = new object[0]; IntPtr Pixels = Marshal.AllocCoTaskMem(c); try { this.bitmap.ReadPixels(ImageInfo, Pixels, ImageInfo.RowBytes, 0, 0); using (SKData Data = SKData.Create(Pixels, c)) { SKImage Result = SKImage.FromPixels(new SKImageInfo(ImageInfo.Width, ImageInfo.Height, SKColorType.Bgra8888), Data, ImageInfo.RowBytes); Pixels = IntPtr.Zero; return(Result); } } finally { if (Pixels != IntPtr.Zero) { Marshal.FreeCoTaskMem(Pixels); } } }
public static WriteableBitmap ToWriteableBitmap(this SKBitmap skiaBitmap) { using (var image = SKImage.FromPixels(skiaBitmap.PeekPixels())) { return(image.ToWriteableBitmap()); } }
public static Stream GetStream(SKBitmap bitmap) { Stream ms = new MemoryStream(); if (bitmap == null) { return(null); } try { IntPtr p; IntPtr pixels = bitmap.GetPixels(out p); // this line and the next using (var img = SKImage.FromPixels(bitmap.Info, pixels, bitmap.Width * bitmap.BytesPerPixel)) { var data = img.Encode(SKEncodedImageFormat.Png, 100); data.SaveTo(ms); } ms.Position = 0; } catch (Exception ex) { return(null); // TODO log error } return(ms); //await Context.Channel.SendFileAsync(ms, "test.png"); }
//public async Task<string> CropForSquareAsync(string sourceFilePath, string cropedFilePath, // int height, int quality = 100) //{ //} public async Task <string> ResizeByHeightAsync(string sourceFilePath, string resizedFilePath, int resizedHeight, int quality = 100) { resizedFilePath = EnsureTargetFilePath(resizedFilePath); using var sourceFileStream = File.OpenRead(sourceFilePath); using var memStream = new MemoryStream(); try { await sourceFileStream.CopyToAsync(memStream); memStream.Seek(0, SeekOrigin.Begin); var bitmap = SKBitmap.Decode(memStream); var resizeInfo = new SKImageInfo(resizedHeight * bitmap.Width / bitmap.Height, resizedHeight); using var resizedBitmap = bitmap.Resize(resizeInfo, SKFilterQuality.High); using var newImg = SKImage.FromPixels(resizedBitmap.PeekPixels()); using var data = newImg.Encode(SKEncodedImageFormat.Jpeg, quality); using var imgStream = data.AsStream(); using var resizedFileStream = File.OpenWrite(resizedFilePath); imgStream.Seek(0, SeekOrigin.Begin); await imgStream.CopyToAsync(resizedFileStream); return(resizedFilePath); } catch (Exception e) { _logger.LogError(e, e.Message); return(null); } }
internal static Bitmap ColorizeImage(Bitmap baseImage, Color newColor, SKBlendMode blendMode, byte alpha = 255) { BitmapData data = baseImage.LockBits(new Rectangle(0, 0, baseImage.Width, baseImage.Height), ImageLockMode.WriteOnly, baseImage.PixelFormat); var info = new SKImageInfo(baseImage.Width, baseImage.Height); using (SKSurface surface = SKSurface.Create(info, data.Scan0, baseImage.Width * 4)) using (SKImage image = SKImage.FromPixels(info, data.Scan0, baseImage.Width * 4)) using (var paint = new SKPaint()) { SKColor color = newColor.ToSKColor(); paint.Color = color; paint.BlendMode = SKBlendMode.SrcIn; surface.Canvas.DrawPaint(paint); using (SKImage img2 = surface.Snapshot()) { surface.Canvas.Clear(); paint.BlendMode = blendMode; paint.Color = new SKColor(color.Red, color.Green, color.Blue, alpha); surface.Canvas.DrawImage(image, SKRect.Create(image.Width, image.Height)); surface.Canvas.DrawImage(img2, SKRect.Create(img2.Width, img2.Height), paint); } } baseImage.UnlockBits(data); return(baseImage); }
public Task <bool> LoadImageAsync(NativeImage image, ImageSource imageSource, CancellationToken cancelationToken = default(CancellationToken)) { ImageSource newSource = null; switch (imageSource) { case SKImageImageSource imageImageSource: newSource = ImageSource.FromStream(() => ToStream(imageImageSource.Image)); break; case SKBitmapImageSource bitmapImageSource: newSource = ImageSource.FromStream(() => ToStream(SKImage.FromBitmap(bitmapImageSource.Bitmap))); break; case SKPixmapImageSource pixmapImageSource: newSource = ImageSource.FromStream(() => ToStream(SKImage.FromPixels(pixmapImageSource.Pixmap))); break; case SKPictureImageSource pictureImageSource: newSource = ImageSource.FromStream(() => ToStream(SKImage.FromPicture(pictureImageSource.Picture, pictureImageSource.Dimensions))); break; } return(handler.LoadImageAsync(image, newSource, cancelationToken)); }
public static Pixbuf ToPixbuf(this SKBitmap skiaBitmap) { using (var image = SKImage.FromPixels(skiaBitmap.PeekPixels())) { return(image.ToPixbuf()); } }
public static Bitmap ToBitmap(this SKPixmap skiaPixamp) { using (var image = SKImage.FromPixels(skiaPixamp)) { var bmp = image.ToBitmap(); return(bmp); } }
public static WriteableBitmap ToWriteableBitmap(this SKBitmap skiaBitmap) { using (var pixmap = skiaBitmap.PeekPixels()) using (var image = SKImage.FromPixels(pixmap)) { var wb = image.ToWriteableBitmap(); GC.KeepAlive(skiaBitmap); return(wb); } }
public static Pixbuf ToPixbuf(this SKBitmap skiaBitmap) { using (var pixmap = skiaBitmap.PeekPixels()) using (var image = SKImage.FromPixels(pixmap)) { var pixbuf = image.ToPixbuf(); GC.KeepAlive(skiaBitmap); return(pixbuf); } }
public static System.Drawing.Bitmap ToBitmap(this SKBitmap skiaBitmap) { using (var pixmap = skiaBitmap.PeekPixels()) using (var image = SKImage.FromPixels(pixmap)) { var bmp = image.ToBitmap(); GC.KeepAlive(skiaBitmap); return(bmp); } }
public void Save(Stream stream) { IntPtr length; using (var image = SKImage.FromPixels(Bitmap.Info, Bitmap.GetPixels(out length), Bitmap.RowBytes)) using (var data = image.Encode()) { data.SaveTo(stream); } }
public static SKImage ConvertPixelsToImage(byte[] data, int width, int height) { SKImage img; using (var ms = new MemoryStream(data)) { SKImageInfo ii = new SKImageInfo(width, height); SKData sKData = SKData.Create(ms); img = SKImage.FromPixels(ii, sKData); } return(img); }
public static void ToSKPixmap(this Bitmap bitmap, SKPixmap pixmap) { // create an image that wraps the existing pixels var info = GetInfo(bitmap); var ptr = bitmap.LockPixels(); var image = SKImage.FromPixels(info, ptr); // read into pixmap (converting if necessary) image.ReadPixels(pixmap, 0, 0); bitmap.UnlockPixels(); }
public static Image GetImageFromBitmap(SKBitmap bitmap) { Image img = new Image(); SKImage image = SKImage.FromPixels(bitmap.PeekPixels()); SKData encoded = image.Encode(); Stream stream = encoded.AsStream(); img.Source = ImageSource.FromStream(() => stream); return(img); }
/// <inheritdoc /> protected override async Task <bool> Render( ThumbnailsRenderContext ctx, ThumbnailsRenderFileInfo fileInfo, ThumbnailsRenderOption option) { // use the following code maybe faster. https://github.com/kleisauke/net-vips/issues/128 // > sourceVipsImage = Image.Thumbnail(localPath, loadImageSize, loadImageSize, noRotate: false); return(await _fileService.ReadFileStream( fileInfo.FileHandle, stream => { var sourceVipsImage = Image.ThumbnailStream( stream, (int)(ThumbnailUtils.DefaultMaxWidth * ctx.Density), height: (int)(ThumbnailUtils.DefaultMaxHeight * ctx.Density), noRotate: false); sourceVipsImage = sourceVipsImage.Colourspace(Enums.Interpretation.Srgb).Cast(Enums.BandFormat.Uchar); if (!sourceVipsImage.HasAlpha()) { sourceVipsImage = sourceVipsImage.Bandjoin(255); } var imageWidth = sourceVipsImage.Width; var imageHeight = sourceVipsImage.Height; var sourceImageDataPtr = sourceVipsImage.WriteToMemory(out _); sourceVipsImage.Close(); try { using var colorspace = SKColorSpace.CreateSrgb(); var sourceImageInfo = new SKImageInfo( imageWidth, imageHeight, SKColorType.Rgba8888, SKAlphaType.Unpremul, colorspace); using var image = SKImage.FromPixels(sourceImageInfo, sourceImageDataPtr, sourceImageInfo.RowBytes); ThumbnailUtils.DrawShadowView(ctx, new SkImageView(image)); } finally { NetVips.NetVips.Free(sourceImageDataPtr); } return ValueTask.FromResult(true); })); }
private async Task ShareEmotion(EmotionData Data) { Chart chart = new BarChart(); chart = DayChart as BarChart; chart.IsAnimated = false; chart.Margin = 20; chart.LabelColor = SKColors.Purple; var bmp = new SKBitmap(500, 500); var canvas = new SKCanvas(bmp); var image = SKImage.FromPixels(bmp.PeekPixels()); chart.DrawContent(canvas, 500, 500); canvas.Save(); using (MemoryStream ms = new MemoryStream()) { image.Encode(SKEncodedImageFormat.Png, 4).AsStream().CopyTo(ms); var str = Convert.ToBase64String(ms.ToArray()); bytes = Convert.FromBase64String(str); } try { PermissionStatus status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage); if (status != PermissionStatus.Granted) { var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Storage }); status = results[Permission.Storage]; } if (status != PermissionStatus.Granted) { return; } else { DependencyService.Get <IShare>() .ShareContent("", "AboutSelf", ImageSource.FromStream(() => new MemoryStream(bytes))); } } catch (Exception ex) { Debug.WriteLine(ex); } }
public static SKImage ToBitmap(int[] ColorIndex, int Width, int Height, SKColor[] Palette) { int N = Palette.Length; byte[] reds = new byte[N]; byte[] greens = new byte[N]; byte[] blues = new byte[N]; SKColor cl; int x; for (x = 0; x < N; x++) { cl = Palette[x]; reds[x] = cl.Red; greens[x] = cl.Green; blues[x] = cl.Blue; } int Size = Width * Height; int Size4 = Size * 4; byte[] rgb = new byte[Size4]; int Index, Index2; int d; for (Index = Index2 = 0; Index < Size; Index++) { d = ColorIndex[Index]; if (d < 0 || d >= N) { rgb[Index2++] = 0; rgb[Index2++] = 0; rgb[Index2++] = 0; rgb[Index2++] = 255; } else { rgb[Index2++] = blues[d]; rgb[Index2++] = greens[d]; rgb[Index2++] = reds[d]; rgb[Index2++] = 255; } } using (SKData Data = SKData.Create(new MemoryStream(rgb))) { return(SKImage.FromPixels(new SKImageInfo(Width, Height, SKColorType.Bgra8888), Data, Width * 4)); } }
/// <summary> /// Converts an image to a SkiaSharp SKImage. /// </summary> /// <param name="image">Image to convert to SKImage type.</param> /// <returns>SKImage.</returns> internal static SKImage AsSKImage(this ImageBase image) { var data = SKData.Create(image.ImageData, image.Size); var colorType = image.PixelFormat switch { // These are unsupported by SkiaSharp: BGRX_32bpp, BGR_24bpp, Gray_16bpp, RGBA_64bpp PixelFormat.BGRA_32bpp => SKColorType.Bgra8888, PixelFormat.Gray_8bpp => SKColorType.Gray8, PixelFormat.Undefined => SKColorType.Unknown, PixelFormat.Gray_16bpp => throw new ArgumentException($"Unsupported pixel format: {image.PixelFormat} (e.g. DepthImage)"), _ => throw new ArgumentException($"Unsupported pixel format: {image.PixelFormat}"), }; var info = new SKImageInfo(image.Width, image.Height, colorType); return(SKImage.FromPixels(info, data, image.Stride)); }
private static void DrawAttachedPicture(ThumbnailsRenderContext ctx, MediaStream attachedPicStream) { using var attachedPicture = attachedPicStream.ReadAttachedPicture(); var attachedPictureVipsImage = Image.ThumbnailStream( attachedPicture, (int)(ThumbnailUtils.DefaultMaxWidth * ctx.Density), height: (int)(ThumbnailUtils.DefaultMaxHeight * ctx.Density), noRotate: false); attachedPictureVipsImage = attachedPictureVipsImage.Colourspace(Enums.Interpretation.Srgb).Cast(Enums.BandFormat.Uchar); if (!attachedPictureVipsImage.HasAlpha()) { attachedPictureVipsImage = attachedPictureVipsImage.Bandjoin(255); } var imageWidth = attachedPictureVipsImage.Width; var imageHeight = attachedPictureVipsImage.Height; var sourceImageDataPtr = attachedPictureVipsImage.WriteToMemory(out _); attachedPictureVipsImage.Close(); try { using var colorspace = SKColorSpace.CreateSrgb(); var sourceImageInfo = new SKImageInfo( imageWidth, imageHeight, SKColorType.Rgba8888, SKAlphaType.Unpremul, colorspace); using var image = SKImage.FromPixels(sourceImageInfo, sourceImageDataPtr, sourceImageInfo.RowBytes); _cachedDecorationImage ??= SKImage.FromEncodedData(ReadDecorationImage()); ThumbnailUtils.DrawShadowView( ctx, new SkImageView(image), _cachedDecorationImage, new SKColor(0, 0, 0), minSize: new SKSize(24, 24)); } finally { NetVips.NetVips.Free(sourceImageDataPtr); } }