-
-
Save Y4er/6b956d7416fa6d4181a511f146ec6e01 to your computer and use it in GitHub Desktop.
netcore SkiaSharp Compress Resize Add Image Watermark
This file contains hidden or 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
static void Resize(string filepath, int quality = 75, string watermarkpath = @"C:\Users\ddd\Desktop\123\water.png") | |
{ | |
using (var water = File.OpenRead(watermarkpath)) | |
{ | |
SKBitmap waterBitmap = SKBitmap.Decode(water); | |
using (var file = File.OpenRead(filepath)) | |
{ | |
var rawLength = file.Length; | |
if (filepath.EndsWith("gif")) | |
{ | |
return; | |
} | |
SKBitmap bitmap = SKBitmap.Decode(file); | |
SKBitmap resizeBitmap = bitmap.Resize(new SKImageInfo(bitmap.Width, bitmap.Height), SKFilterQuality.High); | |
using (var surface = SKSurface.Create(resizeBitmap.Info)) | |
{ | |
SKCanvas canvas = surface.Canvas; | |
canvas.Clear(SKColors.White); | |
canvas.DrawBitmap(bitmap, 0, 0); | |
if (bitmap.Width < waterBitmap.Width || bitmap.Height < waterBitmap.Height) | |
{ | |
Console.WriteLine("水印大于图片,跳过此图片."); | |
} | |
else | |
{ | |
canvas.DrawBitmap(waterBitmap, bitmap.Width - waterBitmap.Width, bitmap.Height - waterBitmap.Height); | |
} | |
using (SKImage img = surface.Snapshot()) | |
{ | |
SKData data = img.Encode(SKEncodedImageFormat.Jpeg, quality); | |
var result = ((rawLength - data.ToArray().Length) * 100 / rawLength); | |
Console.WriteLine($"{file.Name} resized size:{data.ToArray().Length} raw size:{rawLength} change:{result}%"); | |
File.WriteAllBytes(filepath, data.ToArray()); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment