Necesito convertir la imagen a URL de datos (imagen incrustada) en la aplicación Win para HTML y necesito URL de datos (imagen incrustada) en la imagen.cómo convertir Image to Data URI para Html con C#?
31
A
Respuesta
54
public static string GetDataURL(string imgFile)
{
return "<img src=\"data:image/"
+ Path.GetExtension(imgFile).Replace(".","")
+ ";base64,"
+ Convert.ToBase64String(File.ReadAllBytes(imgFile)) + "\" />";
}
+0
@Andrew: Agregue la respuesta técnicamente correcta. – Ankur
21
¿No es una URL de datos solo la base de la imagen 64 codificada?
Entonces esto debería hacerlo.
var bytes = File.ReadAllBytes("C:\\somepath\\picture.png");
var b64String = Convert.ToBase64String(bytes);
var dataUrl = "data:image/png;base64," + b64String;
5
Si está utilizando ASP.NET MVC, reveló un poco de código Ankur's answer podría ser más conveniente:
public static string DataUriContent(this UrlHelper url, string path)
{
var filePath = HttpContext.Current.Server.MapPath(path);
var sb = new StringBuilder();
sb.Append("data:image/")
.Append((Path.GetExtension(filePath) ?? "png").Replace(".", ""))
.Append(";base64,")
.Append(Convert.ToBase64String(File.ReadAllBytes(filePath)));
return sb.ToString();
}
y el uso (sólo la sustitución de @Url.Content
con @Url.DataUriContent
):
<img src="@Url.DataUriContent("~/Path/To/Image/yourImage.png")"/>
Cuestiones relacionadas
- 1. html to jpg con C#
- 2. ¿Cómo puedo convertir System.Byte [] en Image? (Formas de ventana C#)
- 3. Objeto Byte Array to Image
- 4. Image File to PDF Stream Conversion
- 5. C#: Cómo convertir long to ulong
- 6. PHP HTML image output
- 7. HTML Title Image
- 8. Rendering C# Objects to Html
- 9. PHPMailer, AddStringAttachment y Data URI Scheme
- 10. C# string to html keeping whitespace?
- 11. Convertir archivo uri a contenido uri
- 12. Cómo obtener c buffer desde ImageMagick Image
- 13. Convertir cadena a Uri
- 14. WPF Custom Control: TemplateBinding to Image
- 15. Cómo convertir un archivo: // uri en contenido: // uri?
- 16. C/C++ Image Loading
- 17. zlib de C++ a C# (Cómo convertir byte [] a stream y stream to byte [])
- 18. Cómo convertir HTML a MarkDown en C#?
- 19. Convertir cv :: Mat a Magick :: Image
- 20. C# HTMLAgilityPack HTML to Text - Parse Errors
- 21. Cómo convertir tabla HTML para Javascript Object con jQuery
- 22. Jquery ajax data converter to string
- 23. Clickable Image Map C#
- 24. C# .net convertir HTML a RTF
- 25. SQL Server varbinary (max) a Image data type
- 26. Text-To-Speech con jquery API HTML
- 27. C++ Image Manipulation
- 28. html table to powerpoint
- 29. Java - Convertir cadena en objeto URI válido
- 30. Convertir archivo PDF a HTML en C#
El título hace un mejor trabajo al explicar la pregunta, la pregunta real. –
gracias Jeff, tengo muchas imágenes en el disco local, las imágenes tienen diferentes tamaños, algunas imágenes son grandes y otras son pequeñas. Necesito una solución para convertir algunas imágenes a HTML y usarlas en el navegador web. – hashi