
using FellowOakDicom.Imaging;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using System.Security.Cryptography;
using System.Text;
using Dicom.Imaging;
using DicomImage = FellowOakDicom.Imaging.DicomImage;

namespace IRaCIS.Core.Application.Helper;

public static class ImageHelper
{

    // 采用ImageSharp组件  跨平台，不依赖windows 平台图像处理组件，这里大坑(net 6 下，之前由于Dicom处理最新组件 依赖了这个库的一个旧版本，导致缩略图bug，单独升级依赖组件才解决)
    public static void ResizeSave(string filePath, string? fileStorePath)
    {

        fileStorePath = fileStorePath ?? filePath + ".preview.jpeg";

        using (var image = SixLabors.ImageSharp.Image.Load(filePath))
        {

            image.Mutate(x => x.Resize(500, 500));

            image.Save(fileStorePath);

        }
    }



    public static Stream RenderPreviewJpeg(string filePath)
    {
        string jpegPath = filePath + ".preview.jpg";

        if (!File.Exists(jpegPath)|| new FileInfo(jpegPath).Length==0)
        {
            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);
    }


}



