c#服务器端和Android客户端利用BASE64对图片和字符串进行编码解码操作。
一、Android上传图片到服务器:
客户端是Android,服务器端是c# webservice,编码解码方式如下:
Android客户端对图片进行BASE64编码
Bitmap image = extras.getParcelable("data");
if (image != null) {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 60,stream);
byte[] b = stream.toByteArray(); // 将图片流以字符串形式存储下来
tp = new String(Base64Coder.encodeLines(b));//转换后的字符串,可将该字符串上传至服务器端进行解码
myIndustryImg.setImageBitmap(image);// 把图片显示到头像
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
C#(webservice端)接收BASE64字符串进行解码
C#接收BASE64字符串
public bool uploadImage(string filename, string imageString)
{
ConnCls myconncls = new ConnCls();
string fileName = "F:\\C# Demo\\GainMapWebservice\\images\\" + filename;
System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create);
System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs);
if (!string.IsNullOrEmpty(imageString) && File.Exists(fileName))
{
bw.Write(Convert.FromBase64String(imageString));
}
bw.Close();
fs.Close();
string sql = "insert into tbl_Industry(IndustryImg) values('" + filename + "')";
if (myconncls.ExecuteSql(sql) == true)
{
return true;
}
return false;
}
二、Android 从服务器端获取图片
C#端返回base64字符串
var base64Img = Convert.ToBase64String(System.IO.File.ReadAllBytes("图片保存的路径"));
Android端接收字符串解码并显示图片
Android端接收字符串
public Bitmap stringtoBitmap(String string) {
// 将字符串转换成Bitmap类型
Bitmap bitmap = null;
try {
byte[] bitmapArray;
bitmapArray = Base64.decode(string, Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
bitmapArray.length);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
这篇文档对您是否有帮助?