How can I get image parameters from Sitecore MediaItem?

asp.net-mvc-3, sitecore, sitecore6

Solution

After some time of searching and trying, and testing numerous options, I found very simple solution:

string mediaUrl = Sitecore.Resources.Media.MediaManager.GetMediaUrl(item);

`item` should be an object of `Sitecore.Data.Items.MediaItem` class.

`mediaUrl` variable has following value: `/~/media/001FC62786B044F5888640C7164ED72F.JPG`

Basing on this simple method, I got back to question about Width and Height, and I have written simple class (to make it easy to serialize image to JSON), which will show you how to get all properties from image added via Sitecore CMS:

public class DataItemImage
{
    public string ID { get; set; }
    public string Source { get; set; }
    public string Width { get; set; }
    public string Height { get; set; }
    public string Alt { get; set; }

    public DemoDataItemImage(Sitecore.Data.Fields.ImageField obj)
    {
        string mediaUrl = Sitecore.Resources.Media.MediaManager.GetMediaUrl(obj.MediaItem);
        ID = obj.MediaItem.ID.ToString();
        Source = mediaUrl;
        Width = obj.Width;
        Height = obj.Height;
        Alt = obj.Alt;
    }
}

I have added `Alt` and `ID` parameter as well. There are also other like `Class` and `Border`, but since this things can be set in front-end (HTML + CSS), I didn't add them.

If you want to output this class as a Json, set your controller action to return `JsonResult`, and add this line (where `obj` is an instance of `DataItemImage` class):

return Json(obj, JsonRequestBehavior.AllowGet);

I hope it will help other Sitecore developers as well.

Problem

I need to read image parameters (source, width, height) in controller when I'm building json feed. I made all the steps from this question. But suggested method allows you to get image tag using View Helper, and only inside view context. Since I can't (and really don't want to, as it's really bad practice) create HTMLHelper in Controller I can't generate it there. This method gives me only path to *.ashx, no matter what I set in my web.config file. So I have this *.ashx URL (`/~/media/5EE32493443547ED8DB0B26166209C85.ashx`) but I can't take advantage on it and generate normal *.jpg URL, which is `/~/media/001FC62786B044F5888640C7164ED72F.JPG`. *.ashx URL has ID in it (`5EE32493-4435-47ED-8DB0-B26166209C85`), but *.jpg doesn't... Also when I paste *.ashx URL into browser, server responds with exception that resource couldn't be found.

Original source

Related problems