protected override bool OnDrawn(Cairo.Context cr) { int width, height; if (this.Log().IsEnabled(LogLevel.Trace)) { this.Log().Trace($"Render {renderCount++}"); } if (_dpi == null) { UpdateDpi(); } width = (int)AllocatedWidth; height = (int)AllocatedHeight; var scaledWidth = (int)(width * _dpi.Value); var scaledHeight = (int)(height * _dpi.Value); var info = new SKImageInfo(scaledWidth, scaledHeight, SKImageInfo.PlatformColorType, SKAlphaType.Premul); // reset the bitmap if the size has changed if (bitmap == null || info.Width != bitmap.Width || info.Height != bitmap.Height) { bitmap = new SKBitmap(scaledWidth, scaledHeight, SKColorType.Rgba8888, SKAlphaType.Premul); } using (var surface = SKSurface.Create(info, bitmap.GetPixels(out _))) { surface.Canvas.Clear(SKColors.White); surface.Canvas.Scale((float)_dpi); WUX.Window.Current.Compositor.Render(surface, info); using (var gtkSurface = new Cairo.ImageSurface( bitmap.GetPixels(out _), Cairo.Format.Argb32, bitmap.Width, bitmap.Height, bitmap.Width * 4)) { gtkSurface.MarkDirty(); cr.Scale(1 / _dpi.Value, 1 / _dpi.Value); cr.SetSourceSurface(gtkSurface, 0, 0); cr.Paint(); } } return(true); }
public void SwizzleRedBlueTest() { var info = new SKImageInfo(1, 1); using (var bmp = new SKBitmap(info)) { bmp.Erase((uint)0xFACEB004); Assert.Equal((uint)0xFACEB004, (uint)bmp.GetPixel(0, 0)); SKSwizzle.SwapRedBlue(bmp.GetPixels(), bmp.GetPixels(), 1); Assert.Equal((uint)0xFA04B0CE, (uint)bmp.GetPixel(0, 0)); } }
public TwitchEmote(List <SKBitmap> Emote_frames, SKCodec Codec, string Name, string ImageType, string Id, int ImageScale, byte[] ImageData) { emote_frames = Emote_frames; codec = Codec; name = Name; id = Id; width = Emote_frames.First().Width; height = Emote_frames.First().Height; imageScale = ImageScale; imageData = ImageData; // If we are webp, with zero frame count then we are a static image // Thus we should just treat it as a differnt imageType so we don't animate it imageType = ImageType; if (imageType == "webp" && Codec.FrameCount == 0) { imageType = "webp_static"; } // Split animated image into a list of images if (imageType == "gif" || imageType == "webp") { emote_frames.Clear(); for (int i = 0; i < Codec.FrameCount; i++) { SKImageInfo imageInfo = new SKImageInfo(codec.Info.Width, codec.Info.Height); SKBitmap newBitmap = new SKBitmap(imageInfo); IntPtr pointer = newBitmap.GetPixels(); SKCodecOptions codecOptions = new SKCodecOptions(i); codec.GetPixels(imageInfo, pointer, codecOptions); emote_frames.Add(newBitmap); } } }
/// <summary> /// Converts the BLP to a <see cref="SKBitmap"/>. /// </summary> /// <param name="mipMapLevel">The desired MipMap-Level. If the given level is invalid, the smallest available level is chosen.</param> /// <returns>A new <see cref="SKBitmap"/> instance representing the BLP image.</returns> /// <exception cref="BadImageFormatException"> /// Can be thrown when a project targets .NET framework. A possible fix is to add a reference to the <see cref="SkiaSharp"/> package, /// and to add <PreferredNativeSkiaSharp>x86</PreferredNativeSkiaSharp> to a PropertyGroup in the project's .csproj file. /// Note that you may have to clean and rebuild the project for this to work. /// </exception> public SKBitmap GetSKBitmap(int mipMapLevel = 0) { SKBitmap bitmap; byte[] pixelData; switch (_formatVersion) { case FileContent.JPG: bitmap = GetJpgBitmapBytes(mipMapLevel, out pixelData); Marshal.Copy(pixelData, 0, bitmap.GetPixels(), pixelData.Length); return(bitmap); case FileContent.Direct: pixelData = GetPixels(mipMapLevel, out var width, out var height, _colorEncoding != 3); bitmap = new SKBitmap(width, height); Marshal.Copy(pixelData, 0, bitmap.GetPixels(), pixelData.Length); return(bitmap); default: throw new IndexOutOfRangeException(); } }
public void Present() { _bitmap.LockPixels(); IntPtr length; var pixels = _bitmap.GetPixels(out length); #if WIN32 UnmanagedMethods.BITMAPINFO bmi = new UnmanagedMethods.BITMAPINFO(); bmi.biSize = UnmanagedMethods.SizeOf_BITMAPINFOHEADER; bmi.biWidth = _bitmap.Width; bmi.biHeight = -_bitmap.Height; // top-down image bmi.biPlanes = 1; bmi.biBitCount = 32; bmi.biCompression = (uint)UnmanagedMethods.BitmapCompressionMode.BI_RGB; bmi.biSizeImage = 0; IntPtr hdc = UnmanagedMethods.GetDC(_hwnd.Handle); int ret = UnmanagedMethods.SetDIBitsToDevice(hdc, 0, 0, (uint)_bitmap.Width, (uint)_bitmap.Height, 0, 0, 0, (uint)_bitmap.Height, pixels, ref bmi, (uint)UnmanagedMethods.DIBColorTable.DIB_RGB_COLORS); UnmanagedMethods.ReleaseDC(_hwnd.Handle, hdc); #else throw new NotImplementedException(); #endif _bitmap.UnlockPixels(); }
public static bool FromGif(string srcFile, string outFile, Size size) { using (var sKCodec = SKCodec.Create(srcFile)) { using (var bitmap = new SKBitmap(sKCodec.Info)) { if (bitmap.Height > bitmap.Width) { size.Width = bitmap.Width * size.Height / bitmap.Height; } else { size.Height = bitmap.Height * size.Width / bitmap.Width; } sKCodec.GetPixels(sKCodec.Info, bitmap.GetPixels(), new SKCodecOptions(0)); using (var newBitmap = new SKBitmap(new SKImageInfo(size.Width, size.Height))) { bitmap.ScalePixels(newBitmap, SKFilterQuality.Medium); using (var image = SKImage.FromBitmap(newBitmap)) { using (var output = File.OpenWrite(outFile)) { image.Encode(SKEncodedImageFormat.Jpeg, 100) .SaveTo(output); return(true); } } } } } }
public ThirdPartyEmote(List <SKBitmap> Emote_frames, SKCodec Codec, string Name, string ImageType, string Id, int ImageScale) { emote_frames = Emote_frames; codec = Codec; name = Name; imageType = ImageType; id = Id; width = Emote_frames.First().Width; height = Emote_frames.First().Height; imageScale = ImageScale; if (imageType == "gif") { emote_frames.Clear(); for (int i = 0; i < Codec.FrameCount; i++) { SKImageInfo imageInfo = new SKImageInfo(codec.Info.Width, codec.Info.Height); SKBitmap newBitmap = new SKBitmap(imageInfo); IntPtr pointer = newBitmap.GetPixels(); SKCodecOptions codecOptions = new SKCodecOptions(i); codec.GetPixels(imageInfo, pointer, codecOptions); emote_frames.Add(newBitmap); } } }
SKBitmap FillBitmapBytePtr(out string description, out int milliseconds) { description = "GetPixels byte ptr"; SKBitmap bitmap = new SKBitmap(256, 256); stopwatch.Restart(); IntPtr pixelsAddr = bitmap.GetPixels(); unsafe { for (int rep = 0; rep < REPS; rep++) { byte *ptr = (byte *)pixelsAddr.ToPointer(); for (int row = 0; row < 256; row++) { for (int col = 0; col < 256; col++) { *ptr++ = (byte)(col); // red *ptr++ = 0; // green *ptr++ = (byte)(row); // blue *ptr++ = 0xFF; // alpha } } } } milliseconds = (int)stopwatch.ElapsedMilliseconds; return(bitmap); }
public SKBitmap Convert(byte[] bytes, uint width, uint height) { var bitmap = new SKBitmap((int)width, (int)height); var pixelsAddress = bitmap.GetPixels(); unsafe { var ptr = (byte *)pixelsAddress.ToPointer(); var i = 0; for (var x = 0; x < width; x++) { for (var y = 0; y < height; y++) { *ptr++ = bytes[i++]; // red *ptr++ = bytes[i++]; // green *ptr++ = bytes[i++]; // blue *ptr++ = bytes[i++]; // alpha } } } return(bitmap); }
public static Texture2D CreateXamagonTexture() { // create a SkiaSharp bitmap var info = new SKImageInfo(200, 200); var bmp = new SKBitmap(info); DrawXamagon(bmp); // convert the SkiaSharp color type to a Unity color type TextureFormat format; if (info.ColorType == SKColorType.Bgra8888) { format = TextureFormat.BGRA32; } else { format = TextureFormat.RGBA32; } // create a Unity texture var texture = new Texture2D(info.Width, info.Height, format, false); texture.LoadRawTextureData(bmp.GetPixels(), info.BytesSize); texture.Apply(); return(texture); }
private SKBitmap LoadBitmap(string imagePath) { using (FileStream stream = new FileStream(imagePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (var sKManagedStream = new SKManagedStream(stream)) { using (var codec = SKCodec.Create(sKManagedStream)) { var info = codec.Info; var bitmap = new SKBitmap(info.Width, info.Height, SKImageInfo.PlatformColorType, info.IsOpaque ? SKAlphaType.Opaque : SKAlphaType.Premul); var result = codec.GetPixels(bitmap.Info, bitmap.GetPixels(out _)); if (result == SKCodecResult.Success || result == SKCodecResult.IncompleteInput) { return(bitmap); } else { throw new ArgumentException("Bitmap was not loaded with provided stream data."); } } } } }
protected override void OnDrawSample(SKCanvas canvas, int width, int height) { if (!buildVxs) { destImg = new ActualImage(400, 300, PixelFarm.Agg.PixelFormat.ARGB32); imgGfx2d = new ImageGraphics2D(destImg); //no platform p = new AggCanvasPainter(imgGfx2d); buildVxs = true; ReadAndRender("tahoma.ttf", "A"); } canvas.Clear(SKColors.White); using (SKBitmap bitmap = new SKBitmap(destImg.Width, destImg.Height, false)) { //IntPtr pixelHeader = bitmap.GetPixels(); //byte[] srcBuffer = ActualImage.GetBuffer(destImg); bitmap.LockPixels(); //System.Runtime.InteropServices.Marshal.Copy( // srcBuffer, 0, // pixelHeader, srcBuffer.Length); //bitmap.UnlockPixels(); PixelFarm.Agg.Imaging.BitmapHelper.CopyToGdiPlusBitmapSameSize( destImg, destImg.Width, destImg.Height, destImg.Stride, bitmap.GetPixels()); bitmap.UnlockPixels(); canvas.DrawBitmap(bitmap, 10, 10); } }
private SKBitmap ReadRegion(SizeL location, int level, SizeL size) { Stopwatch sw = new Stopwatch(); sw.Start(); OpenSlide.TraceMsg("start ReadRegion " + level + "/" + location.Height + "_" + location.Width + ": " + GetBytesReadable(size.Width * size.Height * 3)); SKBitmap bmp = new SKBitmap((int)size.Width, (int)size.Height); bmp.SetPixel(0, 0, SKColors.AliceBlue); bmp.LockPixels(); var bmpdata = bmp.GetPixels(); OpenSlide.TraceMsg("bmp locked " + level + "/" + location.Height + "_" + location.Width); unsafe { void *p = bmpdata.ToPointer(); Import.openslide_read_region(handle, p, location.Width, location.Height, level, size.Width, size.Height); } OpenSlide.TraceMsg("read finished " + level + "/" + location.Height + "_" + location.Width + ": " + GetBytesReadable(size.Width * size.Height * 3 / Math.Max(sw.ElapsedMilliseconds, 1)) + "/ms"); bmp.UnlockPixels(); OpenSlide.TraceMsg("unlock bits " + level + "/" + location.Height + "_" + location.Width); if (bmp.GetPixel(0, 0) == SKColors.Black) { var error = CheckForLastError(); if (error != null) { throw new ArgumentException($"error reading region loc:{location}, level:{level}, size:{size}" + error); } //else just a black image? } OpenSlide.TraceMsg("end ReadRegion " + level + "/" + location.Height + "_" + location.Width); return(bmp); }
/// <summary> /// Decompress a JPEG image. /// </summary> /// <param name="jpegBuf">Pointer to a buffer containing the JPEG image to decompress. This buffer is not modified.</param> /// <param name="jpegBufSize">Size of the JPEG image (in bytes).</param> /// <param name="destPixelFormat">Pixel format of the destination image (see <see cref="SKColorType"/> "Pixel formats".)</param> /// <param name="flags">The bitwise OR of one or more of the <see cref="TJFlags"/> "flags".</param> /// <returns>Decompressed image of specified format.</returns> /// <exception cref="TJException">Throws if underlying decompress function failed.</exception> /// <exception cref="ObjectDisposedException">Object is disposed and can not be used anymore.</exception> /// <exception cref="NotSupportedException">Convertion to the requested pixel format can not be performed.</exception> public static SKBitmap Decompress(this TJDecompressor @this, IntPtr jpegBuf, ulong jpegBufSize, SKColorType destPixelFormat, TJFlags flags) { _ = @this ?? throw new ArgumentNullException(nameof(@this)); var targetFormat = TJSkiaUtils.ConvertPixelFormat(destPixelFormat); @this.GetImageInfo(jpegBuf, jpegBufSize, targetFormat, out var width, out var height, out var stride, out var outBufSize); var info = new SKImageInfo(width, height, destPixelFormat); if (info.RowBytes != stride) { throw new NotSupportedException($"Skia expected the RowBytes/stride to be {info.RowBytes} for the given parameters but MozJPEG returns {stride}. Those values need to be equal."); } if (info.BytesSize != outBufSize) { throw new NotSupportedException($"Skia expected the BytesSize/number of bytes required to store the bitmap data to be {info.BytesSize} for the given parameters but MozJPEG returns {outBufSize}. Those values need to be equal."); } var dst = new SKBitmap(info); var dstPtr = dst.GetPixels(); @this.Decompress(jpegBuf, jpegBufSize, dstPtr, outBufSize, targetFormat, flags, out _, out _, out _); return(dst); }
private async void RunButton_Click(object sender, RoutedEventArgs e) { var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///test.png")); using (var stream = await file.OpenStreamForReadAsync()) { using (var bitmap = new SKBitmap(960, 720)) { using (var canvas = new SKCanvas(bitmap)) { using (var codec = SKCodec.Create(stream)) { using (var decodeBitmap = new SKBitmap(codec.Info)) { var pointer = decodeBitmap.GetPixels(); codec.GetPixels(decodeBitmap.Info, pointer); var dest = new SKRect(0, 0, 960, 720); var stopwatch = new Stopwatch(); stopwatch.Start(); canvas.DrawBitmap(decodeBitmap, dest); stopwatch.Stop(); await new MessageDialog($"cost {stopwatch.ElapsedMilliseconds} ms").ShowAsync(); } } } } } }
public void DecodingWithPathAndDrawingOnGPUCreatesCorrectImage() { var info = new SKImageInfo(120, 120); var path = Path.Combine(PathToImages, "vimeo_icon_dark.png"); using (var ctx = CreateGlContext()) { ctx.MakeCurrent(); using (var grContext = GRContext.CreateGl()) using (var surface = SKSurface.Create(grContext, true, info)) { var canvas = surface.Canvas; canvas.Clear(SKColors.Crimson); using (var image = SKImage.FromEncodedData(path)) { canvas.DrawImage(image, 0, 0); } using (var bmp = new SKBitmap(info)) { surface.ReadPixels(info, bmp.GetPixels(), info.RowBytes, 0, 0); Assert.Equal(SKColors.Crimson, bmp.GetPixel(3, 3)); Assert.Equal(SKColors.Crimson, bmp.GetPixel(70, 50)); Assert.Equal(new SKColor(23, 35, 34), bmp.GetPixel(40, 40)); } } } }
internal static SKBitmap Decode(string path, bool forceCleanBitmap, IFileSystem fileSystem, ImageOrientation?orientation, out SKCodecOrigin origin) { if (!fileSystem.FileExists(path)) { throw new FileNotFoundException("File not found", path); } var requiresTransparencyHack = TransparentImageTypes.Contains(Path.GetExtension(path) ?? string.Empty); if (requiresTransparencyHack || forceCleanBitmap) { using (var stream = new SKFileStream(NormalizePath(path, fileSystem))) { using (var codec = SKCodec.Create(stream)) { if (codec == null) { origin = GetSKCodecOrigin(orientation); return(null); } // create the bitmap var bitmap = new SKBitmap(codec.Info.Width, codec.Info.Height, !requiresTransparencyHack); if (bitmap != null) { // decode codec.GetPixels(bitmap.Info, bitmap.GetPixels()); origin = codec.Origin; } else { origin = GetSKCodecOrigin(orientation); } return(bitmap); } } } var resultBitmap = SKBitmap.Decode(NormalizePath(path, fileSystem)); if (resultBitmap == null) { return(Decode(path, true, fileSystem, orientation, out origin)); } // If we have to resize these they often end up distorted if (resultBitmap.ColorType == SKColorType.Gray8) { using (resultBitmap) { return(Decode(path, true, fileSystem, orientation, out origin)); } } origin = SKCodecOrigin.TopLeft; return(resultBitmap); }
private void ProcessMaskOverlapsIntoMatrix(SKBitmap skBitmap, UniRectangle2f rect) { IntPtr pixelsAddr = skBitmap.GetPixels(); var topOffset = rect.Top; var bottomOffset = rect.Left; unsafe { byte *ptr = (byte *)pixelsAddr.ToPointer(); //uint* ptr = (uint*)pixelsAddr.ToPointer(); for (int row = 0; row < skBitmap.Height; row++) { for (int col = 0; col < skBitmap.Width; col++) { //var pixel = *ptr++; var blue = *ptr++; // blue var green = *ptr++; // green var red = *ptr++; // red var alpha = *ptr++; // alpha if (!(alpha == 255 && blue == 0 && green == 0 && red == 0) || alpha == 0 /*pixel != 0*/) { var realY = row + (int)topOffset; var realX = col + (int)bottomOffset; _globalMatrix[realY, realX]++; } } } } }
SKBitmap FillBitmapUintPtrColor(out string description, out int milliseconds) { description = "GetPixels SKColor"; SKBitmap bitmap = new SKBitmap(256, 256); stopwatch.Restart(); IntPtr pixelsAddr = bitmap.GetPixels(); unsafe { for (int rep = 0; rep < REPS; rep++) { uint *ptr = (uint *)pixelsAddr.ToPointer(); for (int row = 0; row < 256; row++) { for (int col = 0; col < 256; col++) { *ptr++ = (uint)new SKColor((byte)col, 0, (byte)row); } } } } milliseconds = (int)stopwatch.ElapsedMilliseconds; return(bitmap); }
public CameraAnalyzer(SurfaceView surfaceView) { cameraEventListener = new CameraEventsListener(); cameraController = new CameraController(surfaceView, cameraEventListener); InitTensorflowLineService(); var outputInfo = new SKImageInfo( TensorflowLiteService.ModelInputSize, TensorflowLiteService.ModelInputSize, SKColorType.Rgba8888); inputScaled = new SKBitmap(outputInfo); inputScaledRotated = new SKBitmap(outputInfo); colors = inputScaledRotated.GetPixels(); colorCount = TensorflowLiteService.ModelInputSize * TensorflowLiteService.ModelInputSize; stopwatch = new Stopwatch(); cameraFPSCounter = new FPSCounter((x) => { Stats.CameraFps = x.fps; Stats.CameraMs = x.ms; }); processingFPSCounter = new FPSCounter((x) => { Stats.ProcessingFps = x.fps; Stats.ProcessingMs = x.ms; }); }
private void FixSize() { int width, height; GetPlatformWindowSize(_hwnd, 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); }
protected override void OnDrawSample(SKCanvas canvas, int width, int height) { canvas.Clear(SKColors.White); var paint = new SKPaint { IsStroke = true, StrokeWidth = 3, Color = SampleMedia.Colors.XamarinLightBlue }; using (var stream = new SKManagedStream(SampleMedia.Images.BabyTux)) using (var bigBitmap = SKBitmap.Decode(stream)) { canvas.DrawBitmap(bigBitmap, 10, 10); } using (var stream = new SKManagedStream(SampleMedia.Images.BabyTux)) using (var codec = SKCodec.Create(stream)) { var info = codec.Info; var subset = SKRectI.Create(100, 50, 190, 170); var options = new SKCodecOptions(subset); using (var bitmap = new SKBitmap(subset.Width, subset.Height, info.ColorType, SKAlphaType.Premul)) { var result = codec.GetPixels(bitmap.Info, bitmap.GetPixels(), options); if (result == SKCodecResult.Success || result == SKCodecResult.IncompleteInput) { canvas.DrawBitmap(bitmap, info.Width + 20, subset.Top + 10); } } } }
// Working with a fix sized texture (512x512, 1024x1024, etc.). public Texture(SKBitmap image) { bmp = image.Copy(); this.width = bmp.Width; this.height = bmp.Height; internalBuffer = (byte *)bmp.GetPixels(); }
private void Animation(SKCanvas canvas, Animation img) { if (img.BinaryImage != null && img.BinaryImage.Length > 0) { using (SKStream stream = new SKMemoryStream(img.BinaryImage)) using (SKCodec codec = SKCodec.Create(stream)) { int frameCount = codec.FrameCount; int frame = 0; SKImageInfo imageInfo = new SKImageInfo( codec.Info.Width, codec.Info.Height, codec.Info.ColorType, codec.Info.AlphaType, codec.Info.ColorSpace); var bmp = new SKBitmap(imageInfo); IntPtr pointer = bmp.GetPixels(); SKCodecOptions codecOptions = new SKCodecOptions(frame); codec.GetPixels(imageInfo, pointer, codecOptions); canvas.DrawBitmap(bmp, (float)img.Position.X, (float)img.Position.Y); } } else { throw new Exception("Bitmap not provided"); } }
public PorterDuffBlendModesPage() { InitializeComponent(); dstBitmap = new SKBitmap(BitmapSize, BitmapSize); srcBitmap = new SKBitmap(BitmapSize, BitmapSize); IntPtr dstPtr0 = dstBitmap.GetPixels(); IntPtr srcPtr0 = srcBitmap.GetPixels(); for (int row = 0; row < BitmapSize; row++) { for (int col = 0; col < BitmapSize; col++) { bool isDstOpaque = row < 2 * BitmapSize / 3 && col < 2 * BitmapSize / 3; bool isSrcOpaque = row > BitmapSize / 3 && col > BitmapSize / 3; IntPtr dstPtr = dstPtr0 + 4 * (BitmapSize * row + col); IntPtr srcPtr = srcPtr0 + 4 * (BitmapSize * row + col); unsafe { *(uint *)dstPtr.ToPointer() = isDstOpaque ? 0xFFFF0000 : 0; // 0xFFFFE000 : 0; *(uint *)srcPtr.ToPointer() = isSrcOpaque ? 0xFF0000FF : 0; // 0xFF00FFFF : 0; } } } }
public PixelFormatConversionShim(SKImageInfo destinationInfo, IntPtr framebufferAddress) { _destinationInfo = destinationInfo; _framebufferAddress = framebufferAddress; // Create bitmap using default platform settings _bitmap = new SKBitmap(destinationInfo.Width, destinationInfo.Height); if (!_bitmap.CanCopyTo(destinationInfo.ColorType)) { _bitmap.Dispose(); throw new Exception( $"Unable to create pixel format shim for conversion from {_bitmap.ColorType} to {destinationInfo.ColorType}"); } Surface = SKSurface.Create(_bitmap.Info, _bitmap.GetPixels(), _bitmap.RowBytes); if (Surface == null) { _bitmap.Dispose(); throw new Exception( $"Unable to create pixel format shim surface for conversion from {_bitmap.ColorType} to {destinationInfo.ColorType}"); } SurfaceCopyHandler = Disposable.Create(CopySurface); }
public static void Main(string[] args) { using (var stream = File.OpenRead("test.png")) { using (var bitmap = new SKBitmap(960, 720)) { using (var canvas = new SKCanvas(bitmap)) { using (var codec = SKCodec.Create(stream)) { using (var decodeBitmap = new SKBitmap(codec.Info)) { var pointer = decodeBitmap.GetPixels(); codec.GetPixels(decodeBitmap.Info, pointer); var dest = new SKRect(0, 0, 960, 720); var stopwatch = new Stopwatch(); stopwatch.Start(); canvas.DrawBitmap(decodeBitmap, dest); stopwatch.Stop(); Console.WriteLine($"cost {stopwatch.ElapsedMilliseconds} ms"); } } } } } Console.ReadLine(); }
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"); }
private static ImageBrush ReadImageBrushFromFile(Stream stream, PhotoLoadType loadType) { switch (loadType) { case PhotoLoadType.Miniature: using (var src = SKBitmap.Decode(stream)) { var scale = 100f / src.Width; var resized = new SKBitmap( (int)(src.Width * scale), (int)(src.Height * scale), src.ColorType, src.AlphaType); src.ScalePixels(resized, SKFilterQuality.Low); var bitmap = new Bitmap( resized.ColorType.ToPixelFormat(), resized.GetPixels(), new PixelSize(resized.Width, resized.Height), SkiaPlatform.DefaultDpi, resized.RowBytes); return(new ImageBrush(bitmap)); } break; case PhotoLoadType.Full: return(new ImageBrush(new Bitmap(stream))); break; default: throw new Exception($"invalid ImageLoadMode:{loadType.ToString()}"); } }
public static byte[] GetBitmapData(SKBitmap bmp) { var ptr = bmp.GetPixels(); var data = new byte[bmp.Width * bmp.Height * 4]; Marshal.Copy(ptr, data, 0, data.Length); return(data); }