100 lines
2.7 KiB
C#
100 lines
2.7 KiB
C#
|
||
using FellowOakDicom.Imaging;
|
||
using SixLabors.ImageSharp;
|
||
using SixLabors.ImageSharp.Formats.Jpeg;
|
||
using SixLabors.ImageSharp.Processing;
|
||
using SixLabors.ImageSharp.PixelFormats;
|
||
using IRaCIS.Core.Application.Helper;
|
||
using SixLabors.ImageSharp.Drawing.Processing;
|
||
|
||
|
||
|
||
public static class ImageHelper
|
||
{
|
||
|
||
// 采用ImageSharp组件 跨平台,不依赖windows 平台图像处理组件,这里大坑(net 6 下,之前由于Dicom处理最新组件 依赖了这个库的一个旧版本,导致缩略图bug,单独升级依赖组件才解决)
|
||
public static void ResizeSave(string filePath, string? fileStorePath)
|
||
{
|
||
|
||
fileStorePath = fileStorePath ?? filePath + ".preview.jpeg";
|
||
|
||
// 读取 DICOM 文件
|
||
var dicomImage = new DicomImage(filePath);
|
||
|
||
// 渲染 DICOM 图像到 ImageSharp 格式
|
||
using (var image = dicomImage.RenderImage().AsSharpImage())
|
||
{
|
||
// 生成缩略图(调整大小)
|
||
image.Mutate(x => x.Resize(500, 500));
|
||
|
||
// 保存缩略图为 JPEG
|
||
image.Save(fileStorePath, new JpegEncoder());
|
||
}
|
||
|
||
|
||
}
|
||
|
||
|
||
|
||
public static Stream RenderPreviewJpeg(string filePath)
|
||
{
|
||
string jpegPath = filePath + ".preview.jpg";
|
||
|
||
if (!File.Exists(jpegPath))
|
||
{
|
||
using (Stream stream = new FileStream(jpegPath, FileMode.Create))
|
||
{
|
||
DicomImage image = new DicomImage(filePath);
|
||
|
||
var sharpimage = image.RenderImage().AsSharpImage();
|
||
|
||
sharpimage.Save(stream, new JpegEncoder());
|
||
|
||
}
|
||
}
|
||
|
||
return new FileStream(jpegPath, FileMode.Open);
|
||
}
|
||
|
||
public static void RemovePreviewJpeg(string filePath)
|
||
{
|
||
string jpegPath = filePath + ".preview.jpg";
|
||
if (File.Exists(jpegPath)) File.Delete(jpegPath);
|
||
}
|
||
|
||
|
||
|
||
|
||
public static class ImageMaskHelper
|
||
{
|
||
public static async Task MaskAsync(Stream input, Stream output, IEnumerable<MaskRegion> regions)
|
||
{
|
||
// 确保输入流从起始位置读取
|
||
if (input.CanSeek && input.Position != 0)
|
||
{
|
||
input.Position = 0;
|
||
}
|
||
|
||
using var image = await Image.LoadAsync(input);
|
||
|
||
// 保存原始图片的编码格式
|
||
var originalFormat = image.Metadata.DecodedImageFormat;
|
||
|
||
image.Mutate(ctx =>
|
||
{
|
||
foreach (var r in regions)
|
||
{
|
||
ctx.Fill(Color.White, new Rectangle(r.X, r.Y, r.Width, r.Height));
|
||
}
|
||
});
|
||
|
||
// 使用原始格式保存,保持格式不变
|
||
await image.SaveAsync(output, originalFormat);
|
||
}
|
||
}
|
||
|
||
}
|
||
|
||
|
||
|