Android 上传图片到服务器时将bitmap转换为byte[]最后转换为String

时间:2025-02-19 22:53:30
 1. //上传图片到服务器
        Bitmap bitmap = ………………;//得到图片
        ByteArrayOutputStream out=new ByteArrayOutputStream();
        try {
();
(, 100, out);//转换为png格式的
();
} catch (IOException e) {
// TODO Auto-generated catch block
();
}
        byte[] buffer=();
        byte[] encode=(buffer, );

        String photo=new String(encode);


RequestParams params = new RequestParams();
("ImagefileName", fileName);
("filestream", photo);
String url = ();
(url, params, new JsonHttpResponseHandler() {

…………

}

//AccountSafeActivity


2.根据名称以及url返回bitmap

private static Bitmap getNetBitmap(String strUrl, String fileName,
Context context) {
Bitmap bitmap = null;
try {
URL url = new URL(strUrl);
HttpURLConnection con = (HttpURLConnection) ();
(true);
();
InputStream in = ();
bitmap = (in);
FileOutputStream out = (fileName,
Context.MODE_PRIVATE);
(, 100, out);
();
();
();
} catch (Exception e) {
();
} finally {


}

使用方式

//从服务器获取imageUrl

final String imageUrl = ("ImageUrl");
int loadversion = ("Version");
if (!(imageUrl)) {
if (loadversion > version) {
new Thread() {
public void run() {
getNetBitmap(imageUrl, "",
);
}
}.start();
//().setLoadVersion(loadversion);
} else {
if(bitmap==null)
{
bitmap = BitmapFactory
.decodeStream(
.openFileInput(""));
(new BitmapDrawable(bitmap));
}
if(bitmap==null)
{
(
);
}
}
}
} else {
();
}