C# 图片和base64字符串互转

图片转base64字符串

/// 
/// 图片转base64字符串
/// 
/// 图片路径
private string ImgToBase64String(string Imagefilename)
{
	string strbaser64 = string.Empty;
	try
	{
		Bitmap bmp = new Bitmap(Imagefilename);
		MemoryStream ms = new MemoryStream();
		if (Imagefilename.Contains("jpg"))
		{
			bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
		}
		if (Imagefilename.Contains("png"))
		{
			bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
		}
		byte[] arr = new byte[ms.Length];
		ms.Position = 0;
		ms.Read(arr, 0, (int)ms.Length);
		ms.Close();


		strbaser64 = Convert.ToBase64String(arr);
	}
	catch (Exception ex)
	{
		MessageBox.Show("To64 转换失败\n错误信息:" + ex.Message);
	}
	return strbaser64;
}

Base64转图片

/// 
/// Base64转图片
/// 
/// 文件名
/// 文件base64码
/// 
private Bitmap Base64StringToImage(string ImageName, string base64)
{
	Bitmap bmp = null;
	try
	{
		byte[] arr = Convert.FromBase64String(base64);

		MemoryStream ms = new MemoryStream(arr);
		bmp = new Bitmap(ms);
		if (ImageName.Contains("jpg"))
		{
			bmp.Save(ImageName + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
		}
		if (ImageName.Contains("png"))
		{
			bmp.Save(ImageName + ".png", System.Drawing.Imaging.ImageFormat.Png);
		}
		ms.Close();

	}
	catch (Exception ex)
	{
		MessageBox.Show("ToImg 转换失败\n错误信息:" + ex.Message);
	}
	return bmp;
}

你可能感兴趣的:(c#)