借助网络配置,控制Modbus工具的日志显示,避免卡死界面
智能大石头 authored at 2021-12-11 22:09:19
10.33 KiB
XCoder
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using NewLife;
using SkiaSharp;

namespace NewLife.XCoder.Tools.Image;

/// <summary>水印与缩放参数</summary>
public sealed class WatermarkOptions
{
    /// <summary>水印文字,为空则只做缩放与格式转换</summary>
    public String Text { get; set; } = "";

    /// <summary>字号(按原图像素)</summary>
    public Single FontSize { get; set; } = 24;

    /// <summary>文字颜色,#RRGGBB 或 #AARRGGBB</summary>
    public String ColorHex { get; set; } = "#FFFFFF";

    /// <summary>不透明度 0~1</summary>
    public Single Opacity { get; set; } = 0.6f;

    /// <summary>位置:left-top / center / right-bottom / left-bottom / right-top</summary>
    public String Position { get; set; } = "right-bottom";

    /// <summary>边距(像素)</summary>
    public Int32 Margin { get; set; } = 8;

    /// <summary>最大宽度,0 表示不缩放</summary>
    public Int32 MaxWidth { get; set; }

    /// <summary>最大高度,0 表示不缩放</summary>
    public Int32 MaxHeight { get; set; }

    /// <summary>输出格式(png / jpg / webp),空则跟随目标扩展名</summary>
    public String Format { get; set; } = "";

    /// <summary>JPEG/WebP 质量 1~100</summary>
    public Int32 Quality { get; set; } = 90;
}

/// <summary>图片批处理:缩放、加文字水印、格式转换</summary>
/// <remarks>
/// 基于 SkiaSharp(Avalonia 已带该依赖),Windows/Linux/macOS 行为一致。
/// 定位与缩放这类几何计算单独抽成静态方法,便于在没有图片的情况下也能验证。
/// </remarks>
public static class ImageBatch
{
    /// <summary>支持的图片扩展名</summary>
    public static IReadOnlyList<String> Extensions { get; } = [".png", ".jpg", ".jpeg", ".bmp", ".gif", ".webp"];

    /// <summary>按最大边计算缩放后的尺寸(不放大)</summary>
    /// <param name="width">原宽</param>
    /// <param name="height">原高</param>
    /// <param name="maxWidth">最大宽,0 不限</param>
    /// <param name="maxHeight">最大高,0 不限</param>
    /// <returns>缩放后尺寸</returns>
    public static (Int32 width, Int32 height) ComputeScale(Int32 width, Int32 height, Int32 maxWidth, Int32 maxHeight)
    {
        if (width <= 0 || height <= 0) return (width, height);

        var ratioW = maxWidth > 0 ? (Double)maxWidth / width : 1.0;
        var ratioH = maxHeight > 0 ? (Double)maxHeight / height : 1.0;

        var ratio = Math.Min(ratioW, ratioH);

        // 只在需要缩小时应用
        if (ratio >= 1 || ratio <= 0) return (width, height);

        var w = Math.Max(1, (Int32)Math.Round(width * ratio));
        var h = Math.Max(1, (Int32)Math.Round(height * ratio));

        return (w, h);
    }

    /// <summary>计算水印左上角坐标</summary>
    /// <param name="imageWidth">画布宽</param>
    /// <param name="imageHeight">画布高</param>
    /// <param name="textWidth">文字宽</param>
    /// <param name="textHeight">文字高</param>
    /// <param name="position">位置关键字</param>
    /// <param name="margin">边距</param>
    /// <returns>坐标</returns>
    public static (Single x, Single y) PositionOf(Int32 imageWidth, Int32 imageHeight, Single textWidth, Single textHeight, String? position, Int32 margin = 8)
    {
        var key = (position ?? "").Trim().ToLowerInvariant();

        var left = (Single)margin;
        var top = (Single)margin;
        var right = imageWidth - textWidth - margin;
        var bottom = imageHeight - textHeight - margin;
        var centerX = (imageWidth - textWidth) / 2;
        var centerY = (imageHeight - textHeight) / 2;

        var (x, y) = key switch
        {
            "left-top" => (left, top),
            "right-top" => (right, top),
            "left-bottom" => (left, bottom),
            "center" => (centerX, centerY),
            _ => (right, bottom),
        };

        // 文字比图片还大时不出现负坐标
        return (Math.Max(0, x), Math.Max(0, y));
    }

    /// <summary>解析颜色文本(支持 #RRGGBB 与 #AARRGGBB)</summary>
    /// <param name="hex">颜色文本</param>
    /// <returns>颜色;无法解析时返回白色</returns>
    public static SKColor ParseColor(String? hex)
    {
        if (hex.IsNullOrWhiteSpace()) return SKColors.White;

        var text = hex!.Trim().TrimStart('#');
        if (text.Length == 8 && UInt32.TryParse(text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var argb))
            return new SKColor((Byte)(argb >> 16), (Byte)(argb >> 8), (Byte)argb, (Byte)(argb >> 24));

        if (text.Length == 6 && UInt32.TryParse(text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var rgb))
            return new SKColor((Byte)(rgb >> 16), (Byte)(rgb >> 8), (Byte)rgb);

        if (text.Length == 3 &&
            Int32.TryParse(text[0].ToString(), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var r) &&
            Int32.TryParse(text[1].ToString(), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var g) &&
            Int32.TryParse(text[2].ToString(), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var b))
            return new SKColor((Byte)(r * 17), (Byte)(g * 17), (Byte)(b * 17));

        return SKColors.White;
    }

    /// <summary>处理单张图片</summary>
    /// <param name="sourcePath">源文件</param>
    /// <param name="destPath">目标文件(扩展名决定格式,除非 <see cref="WatermarkOptions.Format"/> 指定)</param>
    /// <param name="options">参数</param>
    /// <returns>目标文件路径</returns>
    /// <exception cref="IOException">源文件无法解码</exception>
    public static String ProcessFile(String sourcePath, String destPath, WatermarkOptions options)
    {
        if (sourcePath.IsNullOrWhiteSpace()) throw new ArgumentException("源文件为空", nameof(sourcePath));
        if (destPath.IsNullOrWhiteSpace()) throw new ArgumentException("目标文件为空", nameof(destPath));
        if (options == null) throw new ArgumentNullException(nameof(options));

        using var input = File.OpenRead(sourcePath!);
        using var origin = SKBitmap.Decode(input) ?? throw new IOException($"无法解码图片:{sourcePath}");

        var (width, height) = ComputeScale(origin.Width, origin.Height, options.MaxWidth, options.MaxHeight);

        using var canvasBitmap = new SKBitmap(width, height, origin.ColorType, origin.AlphaType);
        using (var canvas = new SKCanvas(canvasBitmap))
        {
            canvas.Clear(SKColors.Transparent);
            using var resized = origin.Resize(new SKImageInfo(width, height), SKFilterQuality.High)
                ?? throw new IOException($"缩放大失败:{sourcePath}");
            canvas.DrawBitmap(resized, 0, 0);

            if (!options.Text.IsNullOrWhiteSpace())
            {
                using var paint = new SKPaint
                {
                    IsAntialias = true,
                    Color = ParseColor(options.ColorHex).WithAlpha((Byte)Math.Clamp(options.Opacity * 255, 0, 255)),
                    TextSize = options.FontSize > 0 ? options.FontSize : 24,
                    Typeface = SKTypeface.Default,
                };

                var bounds = new SKRect();
                paint.MeasureText(options.Text, ref bounds);

                var (x, y) = PositionOf(width, height, bounds.Width, bounds.Height, options.Position, options.Margin);
                canvas.DrawText(options.Text, x, y + Math.Abs(bounds.Top), paint);
            }

            canvas.Flush();
        }

        var dir = Path.GetDirectoryName(destPath);
        if (!dir.IsNullOrEmpty()) Directory.CreateDirectory(dir!);

        var format = ResolveFormat(options.Format, destPath!);
        using var image = SKImage.FromBitmap(canvasBitmap);
        using var data = image.Encode(format, Math.Clamp(options.Quality, 1, 100));
        using var output = File.Create(destPath!);

        data.SaveTo(output);

        return destPath!;
    }

    /// <summary>批量处理目录下的图片,输出到目标目录(同名文件)</summary>
    /// <param name="sourceDir">源目录</param>
    /// <param name="destDir">目标目录</param>
    /// <param name="options">参数</param>
    /// <param name="recursive">是否递归子目录</param>
    /// <returns>已生成的文件清单</returns>
    public static IReadOnlyList<String> ProcessDirectory(String sourceDir, String destDir, WatermarkOptions options, Boolean recursive = false)
    {
        var list = new List<String>();
        if (sourceDir.IsNullOrWhiteSpace() || destDir.IsNullOrWhiteSpace()) return list;
        if (!Directory.Exists(sourceDir)) return list;

        var mode = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
        foreach (var file in Directory.GetFiles(sourceDir!, "*", mode))
        {
            var ext = Path.GetExtension(file).ToLowerInvariant();
            if (!Extensions.Contains(ext)) continue;

            var name = Path.GetFileNameWithoutExtension(file);

            var targetExt = options != null && !options.Format.IsNullOrWhiteSpace()
                ? "." + options.Format!.Trim().TrimStart('.').ToLowerInvariant()
                : ext;

            var destPath = Path.Combine(destDir!, name + targetExt);
            list.Add(ProcessFile(file, destPath, options ?? new WatermarkOptions()));
        }

        return list;
    }

    /// <summary>按格式名称或目标扩展名推断编码格式</summary>
    /// <param name="format">格式名,可为空</param>
    /// <param name="path">目标路径或扩展名</param>
    /// <returns>编码格式</returns>
    public static SKEncodedImageFormat ResolveFormat(String? format, String? path)
    {
        var name = (format ?? "").Trim().TrimStart('.').ToLowerInvariant();

        if (name.Length == 0 && !path.IsNullOrWhiteSpace())
        {
            var ext = Path.GetExtension(path!)?.TrimStart('.').ToLowerInvariant();
            if (ext.IsNullOrEmpty()) ext = path!.TrimStart('.').ToLowerInvariant();

            name = ext ?? "";
        }

        return name switch
        {
            "jpg" or "jpeg" => SKEncodedImageFormat.Jpeg,
            "webp" => SKEncodedImageFormat.Webp,
            "gif" => SKEncodedImageFormat.Gif,
            "bmp" => SKEncodedImageFormat.Bmp,
            _ => SKEncodedImageFormat.Png,
        };
    }
}