public MainViewModel() { var color = SKImageInfo.PlatformColorType; var colorString = color == SKColorType.Bgra8888 ? "BGRA" : "RGBA"; ColorCombinations = new ColorCombination[] { new ColorCombination(colorString, color, null), new ColorCombination($"{colorString} (sRGB)", color, SKColorSpace.CreateSrgb()), new ColorCombination("F16 (sRGB Linear)", SKColorType.RgbaF16, SKColorSpace.CreateSrgbLinear()), }; CompilationMessages = new ObservableRangeCollection <CompilationMessage>(); var skiaAss = typeof(SKSurface).Assembly; if (skiaAss.GetCustomAttribute(typeof(AssemblyInformationalVersionAttribute)) is AssemblyInformationalVersionAttribute informational) { SkiaSharpVersion = informational.InformationalVersion; } else if (skiaAss.GetCustomAttribute(typeof(AssemblyFileVersionAttribute)) is AssemblyFileVersionAttribute fileVersion) { SkiaSharpVersion = fileVersion.Version; } else if (skiaAss.GetCustomAttribute(typeof(AssemblyVersionAttribute)) is AssemblyVersionAttribute version) { SkiaSharpVersion = version.Version; } else { SkiaSharpVersion = "<unknown>"; } }
public void CanCreateSrgb() { var colorspace = SKColorSpace.CreateSrgb(); Assert.NotNull(colorspace); Assert.True(SKColorSpace.Equal(colorspace, colorspace)); }
public void SrgbColorsSpaceIsNamedSrgb() { var colorspace = SKColorSpace.CreateSrgb(); Assert.Equal(SKNamedGamma.Srgb, colorspace.NamedGamma); Assert.Equal(SKColorSpaceType.Rgb, colorspace.Type); }
private void DisplayBitmap(SKBitmap image, WriteableBitmap writeableBitmap) { int width = (int)writeableBitmap.Width, height = (int)writeableBitmap.Height; writeableBitmap.Lock(); var skImageInfo = new SKImageInfo() { Width = width, Height = height, ColorType = SKColorType.Bgra8888, AlphaType = SKAlphaType.Premul, ColorSpace = SKColorSpace.CreateSrgb() }; using (var surface = SKSurface.Create(skImageInfo, writeableBitmap.BackBuffer)) { SKCanvas canvas = surface.Canvas; canvas.DrawBitmap(image, new SKPoint(0, 0)); } writeableBitmap.AddDirtyRect(new Int32Rect(0, 0, width, height)); writeableBitmap.Unlock(); }
public void LinearGradientWithIncorrectColorPositionsThrowsColorF() { var colors = new SKColorF[] { SKColors.Blue, SKColors.Yellow, SKColors.Green }; var pos = new float[] { 0f, 0.1f, 0.2f, 0.3f, 0.4f, 1f }; using var colorspace = SKColorSpace.CreateSrgb(); Assert.Throws <ArgumentException>(() => SKShader.CreateLinearGradient(new SKPoint(10, 10), new SKPoint(150, 10), colors, colorspace, pos, SKShaderTileMode.Clamp)); }
public void SrgbColorSpaceIsCorrect() { var colorspace = SKColorSpace.CreateSrgb(); Assert.True(colorspace.IsSrgb); Assert.True(colorspace.GammaIsCloseToSrgb); Assert.False(colorspace.GammaIsLinear); Assert.Equal(SKColorSpaceTransferFn.Srgb, colorspace.GetNumericalTransferFunction()); Assert.Equal(SKColorSpaceXyz.Srgb, colorspace.ToColorSpaceXyz()); }
public void ImageInfoHasColorSpace() { var colorspace = SKColorSpace.CreateSrgb(); var info = new SKImageInfo(100, 100, SKImageInfo.PlatformColorType, SKAlphaType.Premul, colorspace); Assert.Equal(colorspace, info.ColorSpace); var image = SKImage.Create(info); Assert.Equal(colorspace, image.PeekPixels().ColorSpace); }
/// <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); })); }
SKImage ToImage(Texture2D texture) { // Taken form VL.Video.MediaFoundation const int GL_TEXTURE_BINDING_2D = 0x8069; var eglContext = renderContext.EglContext; var eglImage = eglContext.CreateImageFromD3D11Texture(texture.NativePointer); uint textureId = 0; NativeGles.glGenTextures(1, ref textureId); // We need to restore the currently bound texture (https://github.com/devvvvs/vvvv/issues/5925) NativeGles.glGetIntegerv(GL_TEXTURE_BINDING_2D, out var currentTextureId); NativeGles.glBindTexture(NativeGles.GL_TEXTURE_2D, textureId); NativeGles.glEGLImageTargetTexture2DOES(NativeGles.GL_TEXTURE_2D, eglImage); NativeGles.glBindTexture(NativeGles.GL_TEXTURE_2D, (uint)currentTextureId); var description = texture.Description; var colorType = GetColorType(description.Format); var glInfo = new GRGlTextureInfo( id: textureId, target: NativeGles.GL_TEXTURE_2D, format: colorType.ToGlSizedFormat()); var backendTexture = new GRBackendTexture( width: description.Width, height: description.Height, mipmapped: false, glInfo: glInfo); var image = SKImage.FromTexture( renderContext.SkiaContext, backendTexture, GRSurfaceOrigin.BottomLeft, colorType, SKAlphaType.Premul, colorspace: SKColorSpace.CreateSrgb(), releaseProc: _ => { renderContext.MakeCurrent(); backendTexture.Dispose(); NativeGles.glDeleteTextures(1, ref textureId); eglImage.Dispose(); texture.Dispose(); }); return(image); }
public MainViewModel() { var color = SKImageInfo.PlatformColorType; var colorString = color == SKColorType.Bgra8888 ? "BGRA" : "RGBA"; ColorCombinations = new ColorCombination[] { new ColorCombination(colorString, color, null), new ColorCombination($"{colorString} (sRGB)", color, SKColorSpace.CreateSrgb()), new ColorCombination("F16 (sRGB Linear)", SKColorType.RgbaF16, SKColorSpace.CreateSrgbLinear()), }; CompilationMessages = new ObservableRangeCollection <CompilationMessage>(); }
public void CanDrawWithCreateLinearGradientShaderColorF(float[] colorPositions) { var size = 160; var colors = new SKColorF[] { SKColors.Blue, SKColors.Yellow, SKColors.Green }; using var colorspace = SKColorSpace.CreateSrgb(); using var bitmap = new SKBitmap(new SKImageInfo(size, size)); using var canvas = new SKCanvas(bitmap); using var p = new SKPaint { Shader = SKShader.CreateLinearGradient(new SKPoint(10, 10), new SKPoint(150, 10), colors, colorspace, colorPositions, SKShaderTileMode.Clamp) }; canvas.DrawRect(SKRect.Create(size, size), p); }
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); } }
/// <summary> /// Encodes the BlurHash representation of the image. /// </summary> /// <param name="xComponent">The number x components.</param> /// <param name="yComponent">The number y components.</param> /// <param name="filename">The path to an encoded image on the file system.</param> /// <returns>BlurHash representation of the image.</returns> public static string Encode(int xComponent, int yComponent, string filename) { using (SKCodec codec = SKCodec.Create(filename)) { var newInfo = new SKImageInfo() { Width = codec.Info.Width, Height = codec.Info.Height, ColorType = SKColorType.Rgba8888, AlphaType = SKAlphaType.Unpremul, ColorSpace = SKColorSpace.CreateSrgb() }; using (SKBitmap bitmap = SKBitmap.Decode(codec, newInfo)) { return(EncodeInternal(xComponent, yComponent, bitmap)); } } }
public void PrimariesToMatrix44() { var primaries = new float[] { 0.64f, 0.33f, 0.30f, 0.60f, 0.15f, 0.06f, 0.3127f, 0.3290f }; var csp = new SKColorSpacePrimaries(primaries); var matrix44 = csp.ToXyzD50(); Assert.NotNull(matrix44); using var srgb = SKColorSpace.CreateSrgb(); var srgb44 = srgb.ToXyzD50(); AssertSimilar(srgb44.ToRowMajor(), matrix44.ToRowMajor(), PRECISION); }
public void ColorSpaceCorrectlyReferencesSrgbSingleton() { var handle1 = SkiaApi.sk_colorspace_new_srgb(); var colorspace1 = SKColorSpace.CreateSrgb(); Assert.Equal(colorspace1.Handle, handle1); var colorspace2 = SKColorSpace.CreateSrgb(); Assert.Same(colorspace1, colorspace2); Assert.Equal(handle1, colorspace2.Handle); colorspace2.Dispose(); Assert.False(colorspace2.IsDisposed); Assert.False(colorspace1.IsDisposed); SkiaApi.sk_refcnt_safe_unref(handle1); }
/// <summary> /// Resizes the image and encodes the BlurHash representation of the image. /// </summary> /// <param name="xComponent">The number x components.</param> /// <param name="yComponent">The number y components.</param> /// <param name="filename">The path to an encoded image on the file system.</param> /// <param name="maxWidth">The maximum width to resize the image to.</param> /// <param name="maxHeight">The maximum height to resize the image to.</param> /// <returns>BlurHash representation of the image.</returns> public static string Encode(int xComponent, int yComponent, string filename, int maxWidth, int maxHeight) { using (SKCodec codec = SKCodec.Create(filename)) { var width = codec.Info.Width; var height = codec.Info.Height; float scaleFactor = 0; if (width > maxWidth || height > maxHeight) { scaleFactor = ScaleHelper.GetScale(width, height, maxWidth, maxHeight); SKSizeI supportedScale = codec.GetScaledDimensions(scaleFactor); width = supportedScale.Width; height = supportedScale.Height; } var newInfo = new SKImageInfo() { Width = width, Height = height, ColorType = SKColorType.Rgba8888, AlphaType = SKAlphaType.Unpremul, ColorSpace = SKColorSpace.CreateSrgb() }; using (SKBitmap bitmap = SKBitmap.Decode(codec, newInfo)) { if (scaleFactor == 0) { return(EncodeInternal(xComponent, yComponent, bitmap)); } var(scaledWidth, scaledHeight) = ScaleHelper.GetScaleDimensions(bitmap.Width, bitmap.Height, scaleFactor); newInfo = newInfo.WithSize(scaledWidth, scaledHeight); using (SKBitmap scaledBitmap = bitmap.Resize(newInfo, SKFilterQuality.Low)) { return(EncodeInternal(xComponent, yComponent, scaledBitmap)); } } } }
public void LinearShaderDrawColorFCorrectly() { var size = 160; var colors = new SKColorF[] { SKColors.Blue, SKColors.Gray, SKColors.Gray, SKColors.Red }; var positions = new[] { 0.1f, 0.4f, 0.6f, 0.9f }; using var colorspace = SKColorSpace.CreateSrgb(); using var bitmap = new SKBitmap(new SKImageInfo(size, size)); using var canvas = new SKCanvas(bitmap); using var p = new SKPaint { Shader = SKShader.CreateLinearGradient(new SKPoint(10, 10), new SKPoint(150, 10), colors, colorspace, positions, SKShaderTileMode.Clamp) }; canvas.DrawRect(SKRect.Create(size, size), p); Assert.Equal(SKColors.Blue, bitmap.GetPixel(1, 0)); Assert.Equal(SKColors.Gray, bitmap.GetPixel(80, 0)); Assert.Equal(SKColors.Red, bitmap.GetPixel(159, 0)); }
private void SkiaCanvas_Loaded(object sender, RoutedEventArgs e) { var writeableBitmap = new WriteableBitmap(PixelWidth, PixelHeight, 96, 96, PixelFormats.Bgra32, BitmapPalettes.Halftone256Transparent); _writeableBitmap = writeableBitmap; var skImageInfo = new SKImageInfo() { Width = PixelWidth, Height = PixelHeight, ColorType = SKColorType.Bgra8888, AlphaType = SKAlphaType.Premul, ColorSpace = SKColorSpace.CreateSrgb() }; SKSurface surface = SKSurface.Create(skImageInfo, writeableBitmap.BackBuffer); _skSurface = surface; Source = writeableBitmap; }
public void SrgbColorSpaceIsCloseToSrgb() { var colorspace = SKColorSpace.CreateSrgb(); Assert.True(colorspace.GammaIsCloseToSrgb); }
protected virtual SKImage ConvertProfile(SKImage data, float width, float height) { using SKImage srcImg = data; SKImageInfo info = new SKImageInfo((int)width, (int)height, SKImageInfo.PlatformColorType, SKAlphaType.Opaque, SKColorSpace.CreateSrgb()); // this is the important part. set the destination ColorSpace as // `SKColorSpace.CreateSrgb()`. Skia will then be able to automatically convert // the original CMYK colorspace, to this new sRGB colorspace. SKImage newImg = SKImage.Create(info); srcImg.ScalePixels(newImg.PeekPixels(), SKFilterQuality.None); // Remove transparency var bitmap = RemoveTransparency(srcImg); newImg = SKImage.FromBitmap(bitmap); // now when doing this resize, Skia knows the original ColorSpace, and the // destination ColorSpace, and converts the colors from CMYK to sRGB. return(newImg); }
public SKBitmap ImageBufferToSKBitmap(IImageBuffer imageBuffer) { if (imageBuffer == null) { return(null); } imageBuffer = imageBuffer.ToU8(); SKBitmap bitmap = null; SKColorSpace colorSpace = null; if (imageBuffer.Format.ColorSpace == ColorSpace.Srgb) { colorSpace = SKColorSpace.CreateSrgb(); } else if (imageBuffer.Format.ColorSpace == ColorSpace.LinearRgb) { colorSpace = SKColorSpace.CreateSrgbLinear(); } try { // for RGBA-images if (imageBuffer.Format.PixelType == PixelType.U8C3) { // convert to 32bpp var src = imageBuffer is I <byte>?((I <byte>)imageBuffer).Data.Buffer : imageBuffer.ToByteArray(); var dst = new byte[imageBuffer.Height * imageBuffer.Width * 4]; int i = 0, j = 0; while (i < dst.Length) { dst[i + 0] = src[j + 0]; dst[i + 1] = src[j + 1]; dst[i + 2] = src[j + 2]; dst[i + 3] = 0xff; i += 4; j += 3; } SKColorType colorType = SKColorType.Rgba8888; switch (imageBuffer.Format.PixelChannels) { case PixelChannels.Rgb: colorType = SKColorType.Rgba8888; break; case PixelChannels.Bgra: colorType = SKColorType.Bgra8888; break; } using (var pinnedImage = new Utilities.PinnedGCHandle(dst)) { var sourceInfo = new SKImageInfo(imageBuffer.Width, imageBuffer.Height, colorType, SKAlphaType.Opaque); if (colorSpace != null) { sourceInfo.ColorSpace = colorSpace; } bitmap = new SKBitmap(); Debug.Assert(sourceInfo.RowBytes == imageBuffer.Width * 4); if (!bitmap.InstallPixels(sourceInfo, pinnedImage.Pointer)) { throw new Exception("InstallPixels poperation of Skia bitmap failed."); } } } // for RGBA-images else if (imageBuffer.Format.PixelType == PixelType.U8C4) { // try direct copy using (var pinnedImage = imageBuffer.Pin()) { SKAlphaType alphaType = SKAlphaType.Unknown; SKColorType colorType = SKColorType.Rgba8888; switch (imageBuffer.Format.PixelChannels) { case PixelChannels.Rgbx: alphaType = SKAlphaType.Opaque; colorType = SKColorType.Rgba8888; break; case PixelChannels.Rgba: alphaType = SKAlphaType.Unpremul; colorType = SKColorType.Rgba8888; break; case PixelChannels.Bgrx: alphaType = SKAlphaType.Opaque; colorType = SKColorType.Bgra8888; break; case PixelChannels.Bgra: alphaType = SKAlphaType.Unpremul; colorType = SKColorType.Bgra8888; break; } var sourceInfo = new SKImageInfo(imageBuffer.Width, imageBuffer.Height, colorType, alphaType); Debug.Assert(sourceInfo.RowBytes == imageBuffer.Width * 4); if (colorSpace != null) { sourceInfo.ColorSpace = colorSpace; } bitmap = new SKBitmap(); if (!bitmap.InstallPixels(sourceInfo, pinnedImage.Pointer)) { throw new Exception("InstallPixels poperation of Skia bitmap failed."); } } } // for gray-scale else if (imageBuffer.Format.PixelType == PixelType.U8C1) { // try direct copy using (var pinnedImage = imageBuffer.Pin()) { var sourceInfo = new SKImageInfo(imageBuffer.Width, imageBuffer.Height, SKColorType.Gray8); Debug.Assert(sourceInfo.RowBytes == imageBuffer.Width); bitmap = new SKBitmap(); if (!bitmap.InstallPixels(sourceInfo, pinnedImage.Pointer)) { throw new Exception("InstallPixels poperation of Skia bitmap failed."); } } } else { throw new Exception("PixelFormat not yet implemented for preview image."); } SKBitmap result = bitmap; bitmap = null; colorSpace = null; return(result); } finally { if (bitmap != null) { bitmap.Dispose(); if (colorSpace != null) { colorSpace.Dispose(); } } } }
//Note: PM> Install-Package SkiaSharp public static Byte[] shrinkImagePNG(Byte[] originalImage, int max_height = 100, int max_width = 120) { //Code by David Stovell from ideas I found in various posts on the internet //originalImage is the Byte Array from the uploaded file. //max_height and max_width are the dimensions to shrink the image down to. Supply your //own values if you do not want the defaults. //NOTE: This code maintains aspect ratio so for example, a tall, narrow image will // shrink until the height matches max_height but the width will be smaller then max_width. //NOTE: If the image is smaller it will not be enlarged. //NOTE: The MimeType of the resized image is image/png using (SKMemoryStream sourceStream = new SKMemoryStream(originalImage)) { using (SKCodec codec = SKCodec.Create(sourceStream)) { sourceStream.Seek(0); using (SKImage image = SKImage.FromEncodedData(SKData.Create(sourceStream))) { int newHeight = image.Height; int newWidth = image.Width; if (max_height > 0 && newHeight > max_height) { double scale = (double)max_height / newHeight; newHeight = max_height; newWidth = (int)Math.Floor(newWidth * scale); } if (max_width > 0 && newWidth > max_width) { double scale = (double)max_width / newWidth; newWidth = max_width; newHeight = (int)Math.Floor(newHeight * scale); } var info = codec.Info.ColorSpace.IsSrgb ? new SKImageInfo(newWidth, newHeight) : new SKImageInfo(newWidth, newHeight, SKImageInfo.PlatformColorType, SKAlphaType.Premul, SKColorSpace.CreateSrgb()); using (SKSurface surface = SKSurface.Create(info)) { using (SKPaint paint = new SKPaint()) { // High quality without antialiasing paint.IsAntialias = true; paint.FilterQuality = SKFilterQuality.High; // Draw the bitmap to fill the surface surface.Canvas.Clear(SKColors.White); var rect = new SKRect(0, 0, newWidth, newHeight); surface.Canvas.DrawImage(image, rect, paint); surface.Canvas.Flush(); using (SKImage newImage = surface.Snapshot()) { using (SKData newImageData = newImage.Encode()) { return(newImageData.ToArray()); } } } } } } } }
/// <summary> /// Draws all layers on top of a <see cref="SKBitmap"/> /// </summary> /// <param name="document"></param> /// <returns>The <see cref="SKBitmap"/> instance</returns> public static SKBitmap LayersToSKBitmap(this SerializableDocument document) { SKImageInfo info = new(document.Width, document.Height, SKColorType.RgbaF32, SKAlphaType.Unpremul, SKColorSpace.CreateSrgb()); using SKSurface surface = SKSurface.Create(info); SKCanvas canvas = surface.Canvas; using SKPaint paint = new(); foreach (SerializableLayer layer in document) { if (layer.PngBytes == null || layer.PngBytes.Length == 0) { continue; } bool visible = document.Layers.GetFinalLayerVisibilty(layer); if (!visible) { continue; } double opacity = document.Layers.GetFinalLayerOpacity(layer); if (opacity == 0) { continue; } using SKColorFilter filter = SKColorFilter.CreateBlendMode(SKColors.White.WithAlpha((byte)(opacity * 255)), SKBlendMode.DstIn); paint.ColorFilter = filter; canvas.DrawImage(layer.ToSKImage(), layer.OffsetX, layer.OffsetY, paint); } SKBitmap bitmap = new(info); surface.ReadPixels(info, bitmap.GetPixels(), info.RowBytes, 0, 0); return(bitmap); }
public async Task JumboAsync(CommandContext context, DiscordEmoji emote) { try { var emoteUri = new Uri(emote.GetEmojiURL()); using var httpClient = _httpClientFactory.CreateClient(); await using var response = await httpClient.GetStreamAsync(emoteUri); // Workaround httpClient response streams not being allowed to seek around. await using var stream = new MemoryStream(); await response.CopyToAsync(stream); stream.Seek(0, SeekOrigin.Begin); var builder = new DiscordMessageBuilder(); if (emote.IsAnimated) { var filename = Path.GetFileName(emoteUri.LocalPath); await context.RespondAsync(builder.WithFile(filename, stream)); return; } else if (emote.Id == 0) { var filename = Path.GetFileNameWithoutExtension(emoteUri.LocalPath); using var svg = new SKSvg(); if (svg.Load(stream) is { }) { float scaleX = 128 / svg.Picture.CullRect.Height; float scaleY = 128 / svg.Picture.CullRect.Width; using var bitmap = svg.Picture.ToBitmap(SKColors.Transparent, scaleX, scaleY, SKColorType.Rgba8888, SKAlphaType.Premul, SKColorSpace.CreateSrgb()); using var image = SKImage.FromBitmap(bitmap); using var _stream = image.Encode(SKEncodedImageFormat.Webp, 90).AsStream(true); await context.RespondAsync(builder.WithFile(filename + ".webp", _stream)); } }
/// <summary> /// Encodes the BlurHash representation of the image. /// </summary> /// <param name="xComponent">The number x components.</param> /// <param name="yComponent">The number y components.</param> /// <param name="filename">The path to an encoded image on the file system.</param> /// <returns>BlurHash representation of the image.</returns> public static string Encode(int xComponent, int yComponent, string filename) { using (SKCodec codec = SKCodec.Create(filename)) { var newInfo = codec.Info.WithAlphaType(SKAlphaType.Unpremul).WithColorType(SKColorType.Rgba8888).WithColorSpace(SKColorSpace.CreateSrgb()); using (SKBitmap bitmap = SKBitmap.Decode(codec, newInfo)) { return(EncodeInternal(xComponent, yComponent, bitmap)); } } }
public void OnPaint(CefPaintElementType type, CefRectangle[] cefRects, IntPtr buffer, int width, int height) { var image = SKImage.FromPixelCopy(new SKImageInfo(width, height, SKColorType.Bgra8888, SKAlphaType.Premul, SKColorSpace.CreateSrgb()), buffer, width * 4); lock (syncRoot) { rasterImage?.Dispose(); rasterImage = image; } }
public SurfaceRenderer(int width, int height) { FinalBitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Pbgra32, null); var imageInfo = new SKImageInfo(width, height, SKColorType.Bgra8888, SKAlphaType.Premul, SKColorSpace.CreateSrgb()); BackingSurface = SKSurface.Create(imageInfo, FinalBitmap.BackBuffer, FinalBitmap.BackBufferStride); }
public async Task StreamReturnsSimilarImage() { var info = new SKImageInfo(100, 100, SKImageInfo.PlatformColorType, SKAlphaType.Premul, SKColorSpace.CreateSrgb()); using var image = SKImage.Create(info); using var data = image.Encode(); using var stream = data.AsStream(); var source = new StreamImageSource { Stream = token => Task.FromResult(stream) }; var result = await source.ToSKImageAsync(); Assert.NotNull(result); var resultInfo = new SKImageInfo(result.Width, result.Height, result.ColorType, result.AlphaType, result.ColorSpace); Assert.Equal(info, resultInfo); }
private static unsafe bool DrawVideo(Stream videoStream, ThumbnailsRenderContext ctx) { using var formatContext = new FormatContext(videoStream); var stream = formatContext.FindBestVideoStream(); if (stream == null) { return(false); } using var videoStreamDecoder = stream.CreateStreamDecoder(); try { if (videoStreamDecoder.Duration <= 0) { videoStreamDecoder.SeekFrame(10 * 1000000); } if (videoStreamDecoder.Duration > 3) { videoStreamDecoder.SeekFrame(videoStreamDecoder.Duration / 3); } } catch (FFmpegException err) { Console.WriteLine("Seek failed: " + err); } var destinationSize = ThumbnailUtils.ContainSize( new SKSize(videoStreamDecoder.FrameWidth, videoStreamDecoder.FrameHeight), new SKSize(ThumbnailUtils.DefaultMaxWidth * ctx.Density, ThumbnailUtils.DefaultMaxHeight * ctx.Density)).ToSizeI(); var sourcePixelFormat = videoStreamDecoder.PixelFormat; if (!videoStreamDecoder.MoveNext()) { throw new InvalidDataException("Can't decode the video."); } using var vfc = new VideoFrameConverter( videoStreamDecoder.FrameWidth, videoStreamDecoder.FrameHeight, sourcePixelFormat, destinationSize.Width, destinationSize.Height); var convertedFrame = vfc.Convert(videoStreamDecoder.Current.Value); using var colorspace = SKColorSpace.CreateSrgb(); var sourceImageInfo = new SKImageInfo( convertedFrame.width, convertedFrame.height, SKColorType.Rgba8888, SKAlphaType.Unpremul, colorspace); using var image = SKImage.FromPixels(sourceImageInfo, (IntPtr)convertedFrame.data[0], sourceImageInfo.RowBytes); _cachedDecorationImage ??= SKImage.FromEncodedData(ReadDecorationImage()); ThumbnailUtils.DrawShadowView( ctx, new SkImageView(image), _cachedDecorationImage, new SKColor(0, 0, 0), minSize: new SKSize(24, 24)); return(true); }
public ISkiaGpuRenderSession BeginRenderingSession() { var session = _surface.BeginDraw(_vulkanPlatformSurface.Scaling); bool success = false; try { var disp = session.Display; var api = session.Api; var size = session.Size; var scaling = session.Scaling; if (size.Width <= 0 || size.Height <= 0 || scaling < 0) { size = new Avalonia.PixelSize(1, 1); scaling = 1; } lock (GrContext) { GrContext.ResetContext(); var image = _surface.GetImage(); var imageInfo = new GRVkImageInfo() { CurrentQueueFamily = disp.QueueFamilyIndex, Format = (uint)image.Format, Image = image.Handle, ImageLayout = (uint)image.CurrentLayout, ImageTiling = (uint)image.Tiling, ImageUsageFlags = _surface.UsageFlags, LevelCount = _surface.MipLevels, SampleCount = 1, Protected = false, Alloc = new GRVkAlloc() { Memory = image.MemoryHandle, Flags = 0, Offset = 0, Size = _surface.MemorySize } }; var renderTarget = new GRBackendRenderTarget((int)size.Width, (int)size.Height, 1, imageInfo); var surface = SKSurface.Create(GrContext, renderTarget, GRSurfaceOrigin.TopLeft, _surface.IsRgba ? SKColorType.Rgba8888 : SKColorType.Bgra8888, SKColorSpace.CreateSrgb()); if (surface == null) { throw new InvalidOperationException( "Surface can't be created with the provided render target"); } success = true; return(new VulkanGpuSession(GrContext, renderTarget, surface, session)); } } finally { if (!success) { session.Dispose(); } } }