Created
October 20, 2016 14:54
-
-
Save xoofx/a9d08a37c43f692e65df80a1888c488b to your computer and use it in GitHub Desktop.
Resize an image and draw some overlay text with SkiaSharp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// You need to configure your C# project with x86 or x64 platform (Tools\Configuration Manager\Create new Platform on the project) | |
// otherwise the native libSkiaSharp.dll will not get copied | |
using System; | |
using System.IO; | |
using SkiaSharp; | |
namespace TestSkia | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var resizeFactor = 0.5f; | |
var bitmap = SKBitmap.Decode("input.jpg"); | |
var toBitmap = new SKBitmap((int)Math.Round(bitmap.Width * resizeFactor), (int)Math.Round(bitmap.Height * resizeFactor), bitmap.ColorType, bitmap.AlphaType); | |
var canvas = new SKCanvas(toBitmap); | |
// Draw a bitmap rescaled | |
canvas.SetMatrix(SKMatrix.MakeScale(resizeFactor, resizeFactor)); | |
canvas.DrawBitmap(bitmap, 0, 0); | |
canvas.ResetMatrix(); | |
var font = SKTypeface.FromFamilyName("Arial"); | |
var brush = new SKPaint | |
{ | |
Typeface = font, | |
TextSize = 64.0f, | |
IsAntialias = true, | |
Color = new SKColor(255, 255, 255, 255) | |
}; | |
canvas.DrawText("Resized!", 0, bitmap.Height * resizeFactor / 2.0f, brush); | |
canvas.Flush(); | |
var image = SKImage.FromBitmap(toBitmap); | |
var data = image.Encode(SKImageEncodeFormat.Jpeg, 90); | |
using (var stream = new FileStream("output.jpg", FileMode.Create, FileAccess.Write)) | |
data.SaveTo(stream); | |
data.Dispose(); | |
image.Dispose(); | |
canvas.Dispose(); | |
brush.Dispose(); | |
font.Dispose(); | |
toBitmap.Dispose(); | |
bitmap.Dispose(); | |
} | |
} | |
} |
Disposing frees resources earlier. Alternatively you can use using
which will call it automatically for you.
There is an error on the line 36. Changing the SKImageEncodeFormat
to SKEncodedImageFormat
solve that.
Thanks! helped me a lot as I was struggling to get this to work
Please update documenation to reflect
There is an error on the line 36. Changing the SKImageEncodeFormat to SKEncodedImageFormat solve that.
Thanks! i have an other question, how to solve text auto swrap.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do you really need to Dispose of everything created? I don't condemn it, just curious. Most examples I saw, don't use Dispose method.