net-core-html-to-image icon indicating copy to clipboard operation
net-core-html-to-image copied to clipboard

Improvement...

Open raphadesa opened this issue 1 year ago • 0 comments

Hello,

I've seen your source code and I have a suggestion to make:

I have an improvement to submit: If you put a "-" at the end of the argument, then you can directly return the stream without having to generate an image and delete it...


using System.Diagnostics;

namespace HtmlRendered;

/// <summary>
/// Output image format
/// </summary>
public enum ImageFormat
{
    Jpg,
    Png
}

public static class HtmlToImage
{
    public static byte[] getImage(string url, int width = 1024, ImageFormat format = ImageFormat.Jpeg, int quality = 100)
    {
        string text = format.ToString().ToLower();
        var rootDir = Path.Join(System.IO.Directory.GetCurrentDirectory(), "HtmlRenderers");

        var di = new DirectoryInfo(rootDir);

        var exePath = Path.Join(di.FullName, "wkhtmltoimage.exe");

        using (var proc = new Process())
        {
            proc.StartInfo = new ProcessStartInfo
            {
                FileName = exePath,
                Arguments =  $" --quality {quality} --width {width} -f {text} {url} -",                
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                RedirectStandardInput = true,
                CreateNoWindow = true
            };

            proc.Start();

            using (var ms = new MemoryStream())
            {
                proc.StandardOutput.BaseStream.CopyTo(ms);
                return ms.ToArray();
            }
        }       
    }

}

raphadesa avatar Oct 17 '24 09:10 raphadesa