从具有id的url获取图像

时间:2013-11-01 08:21:42

标签: c# asp.net .net image-processing

如何通过提供类似

的网址向客户提供图片
http://mydomain.com/image/123?width=100&height=100

在上面的网址我不想提供像

这样的图片名称
http://mydomain.com/image/manoj.jpg

如何才能在C#.net

中实现

1 个答案:

答案 0 :(得分:0)

我最近通过从Northwind DB创建一个网站来学习ASP.NET MVC。存储在Northwind DB中的一些数据是类别的图像。理想情况下,我会将它们提取到文件中并引用文件,但我想知道是否可以从数据库和浏览器中获取它们。所以我有这个代码。

要获取您正在寻找的网址,您需要使用地图新路线,我需要在我的默认路线之前避免冲突。

        routes.MapRoute(
            name: "Images",
            url: "Image/{id}",
            defaults: new { controller = "Image", action = "GetImageById", id = -1 }
        );

然后在我的ImageController类中,我从Northwind DB中检索图像(作为byte [])并将输出流保存为JPEG

    public void GetImageById(int id)
    {
        if (id == -1)
            return;

        byte[] imageArray = db.Categories.Find(id).Picture;

        using (MemoryStream stream = new MemoryStream())
        {
            // Northwind Category images were designed for MS Access, which expects a 78 byte OLE header
            int offset = 78;
            stream.Write(imageArray, offset, imageArray.Length - offset);

            Image image = Image.FromStream(stream);
            image.Save(HttpContext.Response.OutputStream, ImageFormat.Jpeg);
        }
    }

注意:图片来自System.Drawing

对于ASP.NET,您需要使用URL路由(请参阅http://msdn.microsoft.com/en-us/library/cc668201.aspx)。您可以使用它来映射到.ashx处理程序并使用上面的代码返回图像。 (与Satpal和Vinay完全相同的答案,但代码示例)

相关问题