Reputation: 5592
Can you create a custom httphandler with a custom extension in MVC?
I want an image handler that has the following path (if possible), domain.com/picture/{id of the picture}
Is it possible from inside MVC or do i have to do it in IIS 7?
Upvotes: 3
Views: 2235
Reputation: 316
There's no need to add a httphandler. You should do this in asp.net mvc via a controller example:
public class PictureController : Controller
{
public FileResult GetImage(int pictureID)
{
byte[] fileContents = null;
//Get the file here.
return File(fileContents, "image/jpeg");
}
}
in global.asax you can define
routes.MapRoute("Picture-GetImage", "picture/{pictureID}",
new { controller = "Picture", action = "GetImage" }
You could also use System.Web.Helpers.WebImage helper, or do it manually, example:
public static byte[] ProcessCropResizeImage(string imageurl, Size outputSize)
{
if (File.Exists(imageurl))
{
MemoryStream result = new MemoryStream();
ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(m => m.MimeType == "image/jpeg");
if (codec == null)
throw new ArgumentException(string.Format("Unsupported mimeType specified for encoding ({0})", "image/jpeg"), "encodingMimeType");
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 85L);
using (FileStream fs = File.OpenRead(imageurl))
{
using (Image image = Image.FromStream(fs))
{
using (Bitmap b = new Bitmap(outputSize.Width, outputSize.Height))
{
using (Graphics g = Graphics.FromImage((Image)b))
{
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(image, 0, 0, outputSize.Width, outputSize.Height);
g.DrawImage(image, outputSize.Width, outputSize.Height);
}
b.Save(result, codec, encoderParams);
}
}
}
return result.GetBuffer();
}
return null;
}
Upvotes: 7