C#中将图片转化成base64字符串

厂址:http://www.cnblogs.com/yunfeifei/p/4165351.html

1.在C#中将图片转化成base64字符串:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; namespace ConvertImgToBase64
{
class Program
{
static void Main(string[] args)
{
FileInfo file = new FileInfo("1.png");
var stream = file.OpenRead();
byte[] buffer = new byte[file.Length];
//读取图片字节流
stream.Read(buffer, , Convert.ToInt32(file.Length));
//将base64字符串保存到base64.txt文件中
StreamWriter sw = new StreamWriter("base64.txt",false, Encoding.UTF8);
//将字节流转化成base64字符串
sw.Write(Convert.ToBase64String(buffer));
sw.Close();
Console.WriteLine("Convert successful!");
Console.Read();
}
}
}

64位编码就存在txt文件中了,

2.将base64编码的图片嵌入到css中

.main {
width: 600px;
height: 300px;
background-image:url(data:image/gif;base64,R0lGODlhCAAIAJEAAOnp6eTk5O7m8AAAACH5BAEAAAIALAAAAAAIAAgAAAINjAMJh2q6DnxOVsqmLQA7);
}

页面样式应用main时,显示效果为gif背景:

C#中将图片转化成base64字符串

3.将base64编码的图片直接放到img标签中

<img src="data:image/jpeg;base64,R0lGODlhCAAIAJEAAOnp6eTk5O7m8AAAACH5BAEAAAIALAAAAAAIAAgAAAINjAMJh2q6DnxOVsqmLQA7" alt="Base64 encoded image" /> 

这样也能将字节流加载到页面成jpg图片

上一篇:将图片转化为base64编码字符串


下一篇:Java对网络图片/本地图片转换成Base64编码和解码