Last active
September 15, 2015 09:27
-
-
Save micklaw/5e2c298c57e9e76fa1fc to your computer and use it in GitHub Desktop.
Controller for consuming WebsiteToImage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Drawing.Imaging; | |
using System.IO; | |
using System.Text.RegularExpressions; | |
using System.Web.Mvc; | |
using ScreenGrab.Core.Helpers; | |
namespace ScreenGrab.UI.Controllers | |
{ | |
public class HomeController : Controller | |
{ | |
public ActionResult Index() | |
{ | |
return View(); | |
} | |
public ActionResult Image(string url, int? width = 1800, int? height = null) | |
{ | |
if (string.IsNullOrWhiteSpace(url)) | |
{ | |
throw new ArgumentException("url"); | |
} | |
var regex = new Regex("[^a-zA-Z0-9 -]"); | |
var sluggedUrl = regex.Replace(url, ""); | |
var datetime = DateTime.Now.ToString("ddMMyyyyHHmmss"); | |
var filename = $"{datetime}-{sluggedUrl}.png"; | |
// [ML] - Temporary save path just in case we switch to saving images to serve them up | |
var stream = ConvertHtmlToImage(url, width ?? 1800, height ?? 1400, !height.HasValue); | |
return File(stream, "image/png", filename); | |
} | |
private Stream ConvertHtmlToImage(string url, int width = 1800, int height = 1400, bool useBodyHeight = false) | |
{ | |
if (!string.IsNullOrWhiteSpace(url)) | |
{ | |
using (var screengrab = new WebsiteToImage(url, width, height, useBodyHeight)) | |
{ | |
var bitmap = screengrab.Generate(); | |
var stream = new MemoryStream(); | |
bitmap.Save(stream, ImageFormat.Png); | |
stream.Position = 0; | |
return stream; | |
} | |
} | |
throw new ArgumentException("url"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment