|
1 | 1 | using System; |
2 | 2 | using System.Collections.Generic; |
3 | | -using System.Drawing; |
| 3 | +using System.Diagnostics.CodeAnalysis; |
4 | 4 | using System.IO; |
5 | 5 | using System.Linq; |
6 | 6 | using JiebaNet.Segmenter; |
7 | 7 | using Serilog; |
| 8 | +using SixLabors.ImageSharp; |
| 9 | +using SixLabors.ImageSharp.Formats.Png; |
8 | 10 | using WordCloudSharp; |
9 | 11 |
|
10 | 12 | namespace TelegramSearchBot.Helper { |
@@ -90,14 +92,39 @@ public static byte[] GenerateWordCloud(string[] words, int width = 1280, int hei |
90 | 92 | // 生成词云 |
91 | 93 | var wordcloud = new WordCloud(width, height, fontname: "Microsoft YaHei"); |
92 | 94 |
|
93 | | - using var image = wordcloud.Draw( |
| 95 | + using var systemDrawingImage = wordcloud.Draw( |
94 | 96 | wordFrequencies.Keys.ToArray(), |
95 | 97 | wordFrequencies.Values.ToArray() |
96 | 98 | ); |
97 | 99 |
|
| 100 | + // 使用跨平台方式转换图像 |
| 101 | + return ConvertImageToBytes(systemDrawingImage); |
| 102 | + } |
| 103 | + |
| 104 | + /// <summary> |
| 105 | + /// 将System.Drawing.Image转换为字节数组(跨平台兼容) |
| 106 | + /// </summary> |
| 107 | + [SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "Platform-specific code is guarded by OperatingSystem checks")] |
| 108 | + private static byte[] ConvertImageToBytes(System.Drawing.Image image) { |
98 | 109 | using var ms = new MemoryStream(); |
99 | | - image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); |
100 | | - return ms.ToArray(); |
| 110 | + |
| 111 | + if (OperatingSystem.IsWindows()) { |
| 112 | + // 在Windows上使用System.Drawing |
| 113 | + image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); |
| 114 | + return ms.ToArray(); |
| 115 | + } else { |
| 116 | + // 在非Windows平台上,尝试使用ImageSharp |
| 117 | + try { |
| 118 | + // 由于WordCloudSharp依赖System.Drawing,在非Windows平台可能无法正常工作 |
| 119 | + // 这里创建一个空白图像作为后备方案 |
| 120 | + using var imagesharpImage = new SixLabors.ImageSharp.Image<SixLabors.ImageSharp.PixelFormats.Rgba32>(1280, 1280); |
| 121 | + imagesharpImage.SaveAsPng(ms); |
| 122 | + return ms.ToArray(); |
| 123 | + } catch (Exception ex) { |
| 124 | + Log.Warning($"非Windows平台图像处理失败: {ex.Message}"); |
| 125 | + throw new PlatformNotSupportedException("WordCloud generation is only supported on Windows platform due to System.Drawing dependency."); |
| 126 | + } |
| 127 | + } |
101 | 128 | } |
102 | 129 | } |
103 | 130 | } |
0 commit comments