正在做那个类似于ACDSee的程序, 在写的过程, 想要把Thumbnail文件存储到数据库, 在这个过程中, 就有了以下代码…..
将Jpeg格式转换成Base64String格式:
Image to Base64String
static void CreateImgToBase64(string imagePath)
{
Bitmap bmp = (Bitmap)Image.FromFile(imagePath);
MemoryStream stream = new MemoryStream();
bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
stream.Position = 0;
byte[] data = new byte[stream.Length];
stream.Read(data, 0, (int)stream.Length);
stream.Close();
string base64String = string.Empty;
try
{
base64String = System.Convert.ToBase64String(data, 0, data.Length);
}
catch
{
throw;
}
StreamWriter outFile;
try
{
outFile = new StreamWriter(string.Concat(imagePath, ".txt"), false, Encoding.ASCII);
outFile.Write(base64String);
outFile.Close();
}
catch
{
throw;
}
bmp.Dispose();
}
将Base64String转换回Jpeg:
Base64String to Image
static void CreateBase64StrToImage(string filePath)
{
StreamReader reader =
new StreamReader(filePath);
string str = reader.ReadToEnd();
byte[] bitmapData = new byte[str.Length];
bitmapData = Convert.FromBase64String(FixBase64ForImage(str));
MemoryStream streamBitmap = new MemoryStream(bitmapData);
Bitmap bitImage = new Bitmap((Bitmap)Image.FromStream(streamBitmap));
bitImage.Save(filePath.Substring(0, filePath.Length - 4), System.Drawing.Imaging.ImageFormat.Jpeg);
bitImage.Dispose();
}
static string FixBase64ForImage(string image)
{
StringBuilder sbText =
new StringBuilder(image, image.Length);
sbText.Replace("\r\n", string.Empty);
sbText.Replace(" ", string.Empty);
return sbText.ToString();
}
注意: 这个转换是有损转换, 将Jpeg文件转换成Base64String, 再转换回来成Jpeg的文件明显小于原图(起码我在测试的过程中发现是这样的.)