Skip to content

Instantly share code, notes, and snippets.

@xoofx
Created October 20, 2016 14:54
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save xoofx/a9d08a37c43f692e65df80a1888c488b to your computer and use it in GitHub Desktop.
Save xoofx/a9d08a37c43f692e65df80a1888c488b to your computer and use it in GitHub Desktop.
Resize an image and draw some overlay text with SkiaSharp
// 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();
}
}
}
@JasonSpine
Copy link

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.

@eltiare
Copy link

eltiare commented Oct 6, 2018

Disposing frees resources earlier. Alternatively you can use using which will call it automatically for you.

@JoseluDAM2000
Copy link

There is an error on the line 36. Changing the SKImageEncodeFormat to SKEncodedImageFormat solve that.

@losebyg
Copy link

losebyg commented Sep 20, 2019

Thanks! helped me a lot as I was struggling to get this to work

@davidbuckleyni
Copy link

Please update documenation to reflect

There is an error on the line 36. Changing the SKImageEncodeFormat to SKEncodedImageFormat solve that.

@Aric000
Copy link

Aric000 commented Aug 5, 2022

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