首页 > 代码库 > 将图片内嵌入html
将图片内嵌入html
将图片内嵌入到Html中,最好的方法就是用Base64 string.例如:<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAAJcEhZcwAACxIAAAsSAdLdfvwAAAHgSURBVEhLxdfPRwRhHMfxPS1dl4hO/QFLDBGxZomI/Qv20HWIThER0YrosodO/Q2dIqJrDNFtLxExp4iIiJg+n7HP08wz32fnmX0mDa9+PfPMu9lmZp9aaZr+i+xDEAQuVuAA7uABPiCFx+n3p9ADaW6JS7gPPDAjLl4hgjZIx8vMCi/BDUgHd/EE1lfAFu7CC0gHrOMLdqDUkMKMvoN0oHntQqFjhhehiTM1fcMmWMPXIE1swht0oBTm1StNEEVRlI7H43Q0GonjFudQClfeMoPBII3jGFN+N8alfS14sS2DDnOTdizgWXKbTCb6F6gZpkPQ4ePcgFUYhhl+zeCc4Rh0mI9BaScrjzCv8LYKJ7kBJx5h6qrwpzFQyTPcU2GevrSDlWe4r8K8uaUdrDzDayp8bwxU8gx3VPjCGKjkEX4GfTtt5washsNh9uCgJEmyMD+rn3FcmmfgSeowVwtcOUg7aurJZds4Ls0zrIMO09504C9xRZP18mGeNZcr0oQm8JZdhVKY+NZY+552dAa6ZYZpH6SJPm6hsOqUwsS/d1NnfgULUGjYwrQFvou+E5COPTNMXFtfQt2z50urLyRJVVjhcuUI+CYuhYirUz4cNkA6RoFr2MT/o9Q288xkQesHQmtzgg8gc2kAAAAASUVORK5CYII=">
下面做一个MVC的例子,非常简单:
1.获取图片:
string path = Server.MapPath("/Images/img1.png"); Image img = Image.FromFile(path);
2.写一个扩展方法,将Image对象转换成Base64String
public static string ToBase64(Image image, ImageFormat format) { using (var ms = new MemoryStream()) { // Convert Image to byte[] image.Save(ms, format); byte[] imageBytes = ms.ToArray(); // Convert byte[] to Base64 String string base64String = Convert.ToBase64String(imageBytes); return base64String; }
将图片内嵌入html