public void InitialOffset(int bufferSize) { var memStream = new SKMemoryStream(gAbcs); // Skip a few characters into the memStream, so that bufferedStream represents an offset into // the stream it wraps. var arbitraryOffset = 17; memStream.Skip(arbitraryOffset); var bufferedStream = new SKFrontBufferedManagedStream(memStream, bufferSize); // Since SkMemoryStream has a length, bufferedStream must also. Assert.True(bufferedStream.HasLength); var amountToRead = 10; var bufferedLength = bufferedStream.Length; var currentPosition = 0; // Read the stream in chunks. After each read, the position must match currentPosition, // which sums the amount attempted to read, unless the end of the stream has been reached. // Importantly, the end should not have been reached until currentPosition == bufferedLength. while (currentPosition < bufferedLength) { Assert.False(bufferedStream.IsAtEnd); test_read(bufferedStream, gAbcs.Skip(arbitraryOffset + currentPosition).ToArray(), amountToRead); currentPosition = Math.Min(currentPosition + amountToRead, bufferedLength); Assert.Equal(currentPosition, memStream.Position - arbitraryOffset); } Assert.True(bufferedStream.IsAtEnd); Assert.Equal(bufferedLength, currentPosition); }
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 void IncrementalBuffering(int bufferSize) { var memStream = new SKMemoryStream(gAbcs); var bufferedStream = new SKFrontBufferedManagedStream(memStream, bufferSize); test_hasLength(bufferedStream, memStream); // First, test reading less than the max buffer size. test_read(bufferedStream, gAbcs, bufferSize / 2); // Now test rewinding back to the beginning and reading less than what was // already buffered. test_rewind(bufferedStream, true); test_read(bufferedStream, gAbcs, bufferSize / 4); // Now test reading part of what was buffered, and buffering new data. test_read(bufferedStream, gAbcs.Skip(bufferSize / 4).ToArray(), bufferSize / 2); // Now test reading what was buffered, buffering new data, and // reading directly from the stream. test_rewind(bufferedStream, true); test_read(bufferedStream, gAbcs, bufferSize << 1); // We have reached the end of the buffer, so rewinding will fail. // This test assumes that the stream is larger than the buffer; otherwise the // result of rewind should be true. test_rewind(bufferedStream, false); }
public unsafe void StreamLosesOwnershipAndCanBeDisposedButIsNotActually() { var path = Path.Combine(PathToImages, "color-wheel.png"); var stream = new SKMemoryStream(File.ReadAllBytes(path)); var handle = stream.Handle; Assert.True(stream.OwnsHandle); Assert.False(stream.IgnorePublicDispose); Assert.True(SKObject.GetInstance <SKMemoryStream>(handle, out _)); var codec = SKCodec.Create(stream); Assert.False(stream.OwnsHandle); Assert.True(stream.IgnorePublicDispose); stream.Dispose(); Assert.True(SKObject.GetInstance <SKMemoryStream>(handle, out var inst)); Assert.Same(stream, inst); Assert.Equal(SKCodecResult.Success, codec.GetPixels(out var pixels)); Assert.NotEmpty(pixels); codec.Dispose(); Assert.False(SKObject.GetInstance <SKMemoryStream>(handle, out _)); }
public void StreamPeek2() { var gAbcsString = "abcdefghijklmnopqrstuvwxyz"; var gAbcs = StringUtilities.GetEncodedText(gAbcsString, SKTextEncoding.Utf8); var memStream = new SKMemoryStream(gAbcs); for (var bufferSize = 1; bufferSize < memStream.Length; bufferSize++) { var bufferedStream = new SKFrontBufferedManagedStream(memStream, bufferSize); var peeked = 0; for (var i = 1; !bufferedStream.IsAtEnd; i++) { var unpeekableBytes = compare_peek_to_read(bufferedStream, i); if (unpeekableBytes > 0) { // This could not have returned a number greater than i. Assert.True(unpeekableBytes <= i); // We have reached the end of the buffer. Verify that it was at least // bufferSize. Assert.True(peeked + i - unpeekableBytes >= bufferSize); // No more peeking is supported. break; } peeked += i; } } }
protected override void OnDrawSample(SKCanvas canvas, int width, int height) { string text = "\u03A3 and \u0750"; canvas.Clear(SKColors.White); using (var paint = new SKPaint()) { paint.IsAntialias = true; using (var tf = SKTypeface.FromFile(SampleMedia.Fonts.ContentFontPath)) { paint.Color = SampleMedia.Colors.XamarinGreen; paint.TextSize = 60; paint.Typeface = tf; canvas.DrawText(text, 50, 50, paint); } using (var fileStream = new SKFileStream(SampleMedia.Fonts.ContentFontPath)) using (var tf = SKTypeface.FromStream(fileStream)) { paint.Color = SampleMedia.Colors.XamarinDarkBlue; paint.TextSize = 60; paint.Typeface = tf; canvas.DrawText(text, 50, 100, paint); } using (var resource = SampleMedia.Fonts.EmbeddedFont) using (var memory = new MemoryStream()) { resource.CopyTo(memory); var bytes = memory.ToArray(); using (var stream = new SKMemoryStream(bytes)) using (var tf = SKTypeface.FromStream(stream)) { paint.Color = SampleMedia.Colors.XamarinLightBlue; paint.TextSize = 60; paint.Typeface = tf; canvas.DrawText(text, 50, 150, paint); } } using (var managedResource = SampleMedia.Fonts.EmbeddedFont) using (var managedStream = new SKManagedStream(managedResource, true)) using (var tf = SKTypeface.FromStream(managedStream)) { paint.Color = SampleMedia.Colors.XamarinPurple; paint.TextSize = 60; paint.Typeface = tf; canvas.DrawText(text, 50, 200, paint); } } }
public void StreamPeek() { var gAbcsString = "abcdefghijklmnopqrstuvwxyz"; var gAbcs = StringUtilities.GetEncodedText(gAbcsString, SKTextEncoding.Utf8); var memStream = new SKMemoryStream(gAbcs); test_fully_peekable_stream(memStream, memStream.Length); }
public async Task SaveImage(string path, byte[] imageBytes, int compression = 100) { using var ms = new SKMemoryStream(imageBytes); using var original = SKBitmap.Decode(ms); var resizedHeight = original.Height > 2500 ? original.Height / 2 : original.Height; var resizedWidth = original.Width > 2500 ? original.Width / 2 : original.Width; var imageInfo = new SKImageInfo(resizedWidth, resizedHeight); var resizedBitmap = new SKBitmap(imageInfo); original.ScalePixels(resizedBitmap, SKFilterQuality.High); using var image = SKImage.FromBitmap(resizedBitmap); await using var output = File.OpenWrite(path); image.Encode(SKEncodedImageFormat.Jpeg, compression).SaveTo(output); }
public static SKImage Load(string filePath) { using var image = Pfim.Pfim.FromFile(filePath); var newData = image.Data; var stride = image.Stride; var colorType = SkColorType(image, ref newData, ref stride); var imageInfo = new SKImageInfo(image.Width, image.Height, colorType); using var stream = new SKMemoryStream(newData); using var data = SKData.Create(stream); var fromPixelData = SKImage.FromPixelData(imageInfo, data, stride); return(fromPixelData); }
public void MemoryStreamCanBeForked() { var stream = new SKMemoryStream(new byte[] { 1, 2, 3, 4, 5 }); Assert.Equal(1, stream.ReadByte()); Assert.Equal(2, stream.ReadByte()); var dupe = stream.Fork(); Assert.NotSame(stream, dupe); Assert.IsType <SKStreamImplementation>(dupe); Assert.Equal(3, dupe.ReadByte()); Assert.Equal(3, stream.ReadByte()); Assert.Equal(4, dupe.ReadByte()); Assert.Equal(4, stream.ReadByte()); }
protected override SKTypeface GetTypeface(PdfDictionary fontDescription, PdfStream stream) { var buffer = stream.GetBody(true); var lenght1 = stream.Header[PdfName.Length1] as PdfInteger; var bytes = buffer.ToByteArray(); using (var data = new SKMemoryStream(bytes)) { typeface = SKFontManager.Default.CreateTypeface(data); } if (typeface == null) { typeface = ParseName(fontDescription.Resolve(PdfName.FontName)?.ToString(), stream.Header); } return(typeface); }
protected virtual SKTypeface GetTypeface(PdfDictionary fontDescription, PdfStream stream) { var name = fontDescription.Resolve(PdfName.FontName)?.ToString(); var body = stream.GetBody(true).ToByteArray(); //System.IO.File.WriteAllBytes($"export{name}.ttf", body); var data = new SKMemoryStream(body); var typeface = SKFontManager.Default.CreateTypeface(data); // var typeface = SKTypeface.FromStream(data); if (typeface == null) { typeface = ParseName(name, fontDescription); } return(typeface); }
public unsafe void StreamLosesOwnershipToCodecButIsNotForgotten() { var bytes = File.ReadAllBytes(Path.Combine(PathToImages, "color-wheel.png")); var stream = new SKMemoryStream(bytes); var handle = stream.Handle; Assert.True(stream.OwnsHandle); Assert.True(SKObject.GetInstance <SKMemoryStream>(handle, out _)); var codec = SKCodec.Create(stream); Assert.False(stream.OwnsHandle); stream.Dispose(); Assert.True(SKObject.GetInstance <SKMemoryStream>(handle, out _)); Assert.Equal(SKCodecResult.Success, codec.GetPixels(out var pixels)); Assert.NotEmpty(pixels); }
public unsafe void StreamLosesOwnershipAndCanBeGarbageCollected() { VerifyImmediateFinalizers(); var bytes = File.ReadAllBytes(Path.Combine(PathToImages, "color-wheel.png")); DoWork(out var codecH, out var streamH); CollectGarbage(); Assert.False(SKObject.GetInstance <SKMemoryStream>(streamH, out _)); Assert.False(SKObject.GetInstance <SKCodec>(codecH, out _)); void DoWork(out IntPtr codecHandle, out IntPtr streamHandle) { var codec = CreateCodec(out streamHandle); codecHandle = codec.Handle; CollectGarbage(); Assert.Equal(SKCodecResult.Success, codec.GetPixels(out var pixels)); Assert.NotEmpty(pixels); Assert.True(SKObject.GetInstance <SKMemoryStream>(streamHandle, out var stream)); Assert.False(stream.OwnsHandle); Assert.True(stream.IgnorePublicDispose); } SKCodec CreateCodec(out IntPtr streamHandle) { var stream = new SKMemoryStream(bytes); streamHandle = stream.Handle; Assert.True(stream.OwnsHandle); Assert.False(stream.IgnorePublicDispose); Assert.True(SKObject.GetInstance <SKMemoryStream>(streamHandle, out _)); return(SKCodec.Create(stream)); } }
/// <summary> /// Load embeded font /// </summary> /// <param name="fontName"></param> /// <returns></returns> public static SKTypeface LoadTtfFont(string fontName) { var assembly = typeof(SkiaSharpHelper).GetTypeInfo().Assembly; var file = $"WavesGraphs.Resources.Fonts.{fontName}.ttf"; using (var resource = assembly.GetManifestResourceStream(file)) { using (var memory = new MemoryStream()) { resource?.CopyTo(memory); var bytes = memory?.ToArray(); using (var stream = new SKMemoryStream(bytes)) { return(SKTypeface.FromStream(stream)); } } } }
public void PerfectlySizedBuffer(int bufferSize) { var memStream = new SKMemoryStream(gAbcs); var bufferedStream = new SKFrontBufferedManagedStream(memStream, bufferSize); test_hasLength(bufferedStream, memStream); // Read exactly the amount that fits in the buffer. test_read(bufferedStream, gAbcs, bufferSize); // Rewinding should succeed. test_rewind(bufferedStream, true); // Once again reading buffered info should succeed test_read(bufferedStream, gAbcs, bufferSize); // Read past the size of the buffer. At this point, we cannot return. test_read(bufferedStream, gAbcs.Skip(memStream.Position).ToArray(), 1); test_rewind(bufferedStream, false); }
public unsafe void StreamLosesOwnershipAndCanBeGarbageCollected() { VerifyImmediateFinalizers(); var bytes = File.ReadAllBytes(Path.Combine(PathToFonts, "Distortable.ttf")); DoWork(out var typefaceH, out var streamH); CollectGarbage(); Assert.False(SKObject.GetInstance <SKMemoryStream>(streamH, out _)); Assert.False(SKObject.GetInstance <SKTypeface>(typefaceH, out _)); void DoWork(out IntPtr typefaceHandle, out IntPtr streamHandle) { var typeface = CreateTypeface(out streamHandle); typefaceHandle = typeface.Handle; CollectGarbage(); Assert.NotEmpty(typeface.GetTableTags()); Assert.True(SKObject.GetInstance <SKMemoryStream>(streamHandle, out var stream)); Assert.False(stream.OwnsHandle); Assert.True(stream.IgnorePublicDispose); } SKTypeface CreateTypeface(out IntPtr streamHandle) { var stream = new SKMemoryStream(bytes); streamHandle = stream.Handle; Assert.True(stream.OwnsHandle); Assert.False(stream.IgnorePublicDispose); Assert.True(SKObject.GetInstance <SKMemoryStream>(streamHandle, out _)); return(SKTypeface.FromStream(stream)); } }
protected override SKTypeface GetTypeface(PdfDictionary fontDescription, PdfStream stream) { var name = fontDescription.Resolve(PdfName.FontName)?.ToString(); var buffer = stream.GetBody(true); //var lenght1 = stream.Header[PdfName.Length1] as PdfInteger; //var lenght2 = stream.Header[PdfName.Length2] as PdfInteger; //var lenght3 = stream.Header[PdfName.Length3] as PdfInteger; //var bytes = buffer.GetByteArray(lenght1.IntValue, lenght2.IntValue + lenght3.IntValue); //System.IO.File.WriteAllBytes($"export{name}_part2.psc", bytes); var bytes = buffer.ToByteArray(); var typeface = (SKTypeface)null; using (var data = new SKMemoryStream(bytes)) { typeface = SKFontManager.Default.CreateTypeface(data); } #if DEBUG name = Regex.Replace(name, @"[\/?:*""><|]+", "", RegexOptions.Compiled); try { System.IO.File.WriteAllBytes($"export_{name}.psc", bytes); } catch { } //if (typeface == null) //{ // using (var manifestStream = typeof(Type1Font).Assembly.GetManifestResourceStream(name + ".otf")) // { // if (manifestStream != null) // { // typeface = SKFontManager.Default.CreateTypeface(manifestStream); // } // } //} #endif if (typeface == null) { typeface = ParseName(name, fontDescription); } return(typeface); }
public void StreamPeek3() { var gAbcsString = "abcdefghijklmnopqrstuvwxyz"; var gAbcs = StringUtilities.GetEncodedText(gAbcsString, SKTextEncoding.Utf8); for (var bufferSize = 1; bufferSize < gAbcs.Length; bufferSize++) { var memStream = new SKMemoryStream(gAbcs); var bufferedStream = new SKFrontBufferedManagedStream(memStream, bufferSize); var bytesToPeek = bufferSize + 1; var peekStorage = SKData.Create(bytesToPeek); var readStorage = SKData.Create(bytesToPeek); for (var start = 0; start <= bufferSize; start++) { // Skip to the starting point Assert.Equal(start, bufferedStream.Skip(start)); var bytesPeeked = bufferedStream.Peek(peekStorage.Data, bytesToPeek); if (0 == bytesPeeked) { // Peeking should only fail completely if we have read/skipped beyond the buffer. Assert.True(start >= bufferSize); break; } // Only read the amount that was successfully peeked. var bytesRead = bufferedStream.Read(readStorage.Data, bytesPeeked); Assert.Equal(bytesPeeked, bytesRead); Assert.Equal(peekStorage.ToArray().Take(bytesPeeked), readStorage.ToArray().Take(bytesPeeked)); // This should be safe to rewind. Assert.True(bufferedStream.Rewind()); } } }
public void SkippingDoesNotPreventReading(int bufferSize) { var memStream = new SKMemoryStream(gAbcs); var bufferedStream = new SKFrontBufferedManagedStream(memStream, bufferSize); test_hasLength(bufferedStream, memStream); // Skip half the buffer. bufferedStream.Skip(bufferSize / 2); // Rewind, then read part of the buffer, which should have been read. test_rewind(bufferedStream, true); test_read(bufferedStream, gAbcs, bufferSize / 4); // Now skip beyond the buffered piece, but still within the total buffer. bufferedStream.Skip(bufferSize / 2); // Test that reading will still work. test_read(bufferedStream, gAbcs.Skip(memStream.Position).ToArray(), bufferSize / 4); test_rewind(bufferedStream, true); test_read(bufferedStream, gAbcs, bufferSize); }
public unsafe void StreamLosesOwnershipAndCanBeDisposedButIsNotActually() { var path = Path.Combine(PathToFonts, "Distortable.ttf"); var stream = new SKMemoryStream(File.ReadAllBytes(path)); var handle = stream.Handle; Assert.True(stream.OwnsHandle); Assert.False(stream.IgnorePublicDispose); Assert.True(SKObject.GetInstance <SKMemoryStream>(handle, out _)); var typeface = SKTypeface.FromStream(stream); Assert.False(stream.OwnsHandle); Assert.True(stream.IgnorePublicDispose); stream.Dispose(); Assert.True(SKObject.GetInstance <SKMemoryStream>(handle, out var inst)); Assert.Same(stream, inst); Assert.NotEmpty(typeface.GetTableTags()); typeface.Dispose(); Assert.False(SKObject.GetInstance <SKMemoryStream>(handle, out _)); }
private void Load(SKMemoryStream stream, uint index = 0) { Load(stream.ToHarfBuzzBlob()); }
//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()); } } } } } } } }