我尝试将Base64字符串转换为图像并使用相同的图像设置ImageView。我知道如何在java中完成它,但我在C#中遇到了麻烦。任何人都知道如何在C#中完成它?
我尝试过的一些代码;
public Image Base64ToImage(string base64String)
{
// Convert base 64 string to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
// Convert byte[] to Image
using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
Image image = Image.FromStream(ms, true);
return image;
}
}
答案 0 :(得分:5)
Base64到位图:
public Bitmap Base64ToBitmap(String base64String)
{
byte[] imageAsBytes = Base64.Decode(base64String, Base64Flags.Default);
return BitmapFactory.DecodeByteArray(imageAsBytes, 0, imageAsBytes.Length);
}
Bitmap到Base64:
public String BitmapToBase64(Bitmap bitmap)
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.Compress(Bitmap.CompressFormat.Png, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.ToByteArray();
return Base64.EncodeToString(byteArray, Base64Flags.Default);
}
答案 1 :(得分:3)
图片到Base64字符串, 在线转换 - here
public string ImageToBase64(Image image,
System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream 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;
}
}
Base64字符串到图像, 在线转换 - here
public Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0,
imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
答案 2 :(得分:0)
我假设您的编码数据是某种位图格式?如果是这样,你应该能够做到这样的事情:
public Bitmap Base64ToImage(string base64String)
{
// Convert base 64 string to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
// Convert byte[] to Image
using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
Bitmap image = BitmapFactory.FromStream(ms, true);
return image;
}
}