2010-07-11 8 views
7

He estado buscando en los sitios Beta Exchange Stack y he notado que cada sitio que entra en beta tiene un gráfico en la parte superior con las palabras 'Web Beta' o 'Gaming' Beta 'por ejemplo.Imágenes dinámicas en MVC (Stack Exchange Beta sites)

Me pregunto si estas imágenes se crean individualmente o si se crean dinámicamente de alguna manera? ¿Hay alguna manera de usar MVC.NET para crear PNG sobre la marcha?

Si la respuesta es demasiado complicada para este foro, ¿alguien me puede indicar algún artículo que pueda ayudar?

Gracias de antemano

Sniffer

Respuesta

14

Sí hay una manera de generar y servir las imágenes de forma dinámica con ASP.NET MVC. He aquí un ejemplo:

public class HomeController : Controller 
{ 
    public ActionResult MyImage() 
    { 
     // Load an existing image 
     using (var img = Image.FromFile(Server.MapPath("~/test.png"))) 
     using (var g = Graphics.FromImage(img)) 
     { 
      // Use the Graphics object to modify it 
      g.DrawLine(new Pen(Color.Red), new Point(0, 0), new Point(50, 50)); 
      g.DrawString("Hello World", 
       new Font(FontFamily.GenericSerif, 20), 
       new Pen(Color.Red, 2).Brush, 
       new PointF(10, 10) 
      ); 

      // Write the resulting image to the response stream 
      using (var stream = new MemoryStream()) 
      { 
       img.Save(stream, ImageFormat.Png); 
       return File(stream.ToArray(), "image/png"); 
      } 
     } 
    } 
} 

Y entonces simplemente incluir esta imagen en la vista:

<img src="<%= Url.Action("myimage", "home") %>" alt="my image" /> 
+0

Hola Darin - acaba de decir que no le estoy ignorando. Simplemente no he tenido tiempo de probar tu código todavía. Tan pronto como lo haga (y presumiendo que funciona) lo marcaré como la respuesta. Gracias por tu tiempo. Sniffer – Sniffer

+0

Estoy usando MVC 5 y el código como se muestra no me funcionó. Encontré una publicación [enlace] (http://pawelrychlicki.pl/Home/Details/43/mvc-return-image-dynamically-drawn-in-controller-mvc-3) que solucionó el problema. Simplemente agrega stream.Position = 0; después de la línea img.Save. Espero que ayude a alguien. – user2789697

0

Esto funcionó para mí.

using System.Web.Helpers; 
public class HomeController : Controller 
{ 
    public FileContentResult ImageOutput() 
    { 

     WebImage img = new WebImage("C:\\temp\\blank.jpg")); 

     //Do whatever you want with the image using the WebImage class 

     return new FileContentResult(img.GetBytes(), string.Format("image/{0}",img.ImageFormat)); 
    } 
} 

Para usarlo simplemente hacer lo mismo que dijo Darin

<img src="<%= Url.Action("ImageOutput", "home") %>" alt="my image" /> 
Cuestiones relacionadas