編輯:關於 Android 程式設計
早期上傳圖片多採用 HttpServlet 的方式,實際用過 Base64 之後會發現它比傳統串流上傳方便不少,這裡就把整個流程記錄下來,供大家參考嘗試。
直接把 Bitmap 壓縮並編碼即可:
/**
* 將 Bitmap 轉換成 Base64 字串
* @param bit 傳入的 Bitmap 物件
* @return Base64 字串
*/
public String Bitmap2StrByBase64(Bitmap bit){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bit.compress(CompressFormat.JPEG, 40, bos);// 第二個參數為壓縮品質
byte[] bytes = bos.toByteArray();
return Base64.encodeToString(bytes, Base64.DEFAULT);
}
呼叫 setImgByStr() 方法,第一個參數 imgStr 為 Bitmap 轉出的 Base64 字串,第二個參數 imgName 為含副檔名的圖片名稱(例如 photo.jpg):
public static String host = "https://192.168.1.166:8080/ImageServer/";
public static String getContent(String url) throws Exception {
StringBuilder sb = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpParams httpParams = client.getParams();
// 設定網路逾時參數
HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);
HttpResponse response = client.execute(new HttpGet(url));
HttpEntity entity = response.getEntity();
if (entity != null) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(entity.getContent(), "UTF-8"), 8192);
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
}
return sb.toString();
}
public static HttpResponse post(Map<String, Object> params, String url) {
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("charset", HTTP.UTF_8);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
HttpResponse response = null;
if (params != null && params.size() > 0) {
List<NameValuePair> nameValuepairs = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
nameValuepairs.add(new BasicNameValuePair(key, (String) params.get(key)));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuepairs, HTTP.UTF_8));
response = client.execute(httpPost);
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
response = client.execute(httpPost);
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
public static Object getValues(Map<String, Object> params, String url) {
String token = "";
HttpResponse response = post(params, url);
if (response != null) {
try {
token = EntityUtils.toString(response.getEntity());
response.removeHeaders("operator");
} catch (Exception e) {
e.printStackTrace();
}
}
return token;
}
public static Object setImgByStr(String imgStr, String imgName){
String url = host + "channel-uploadImage.action";
Map<String, Object> params = new HashMap<String, Object>();
params.put("imgStr", imgStr);
params.put("imgName", imgName);
return getValues(params, url);
}
public void uploadPhoto() {
// 取得儲存路徑
HttpServletRequest request = ServletActionContext.getRequest();
String path = ServletActionContext.getServletContext().getRealPath("/") + "upload";
File file = new File(path);
if (!file.exists()) {
file.mkdir();
}
String imgPath = path + request.getParameter("imgName");
String imgStr = request.getParameter("imgStr");
boolean flag = string2Image(imgStr, imgPath);
JacksonUtil.responseJSON(response, flag);
}
/**
* 以 Base64 解碼並生成圖片
* @param imgStr 解碼後的字串
*/
public boolean string2Image(String imgStr, String imgFilePath) {
// 對位元組陣列字串進行 Base64 解碼並生成圖片
if (imgStr == null) return false;
try {
byte[] b = new BASE64Decoder().decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) { // 調整異常資料
b[i] += 256;
}
}
// 生成 Jpeg 圖片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
這樣就完成了!上傳成功時前端會收到 true,失敗則收到 false。整體來說,Base64 的做法省去處理 multipart 的麻煩,特別適合小圖上傳的場景,不過大圖仍需留意字串過長帶來的效能與記憶體問題。
Android Studio 下去不掉標題欄?三種解法與背後的原因
在 Eclipse 時代,要拿掉 Activity 的預設標題欄,我習慣寫這一行: requestWindowFeature(Window.FEATURE_NO_TIT
Android UI 實作(四):雲通訊錄的雲端更新圓形進度條
作者:泥沙磚瓦漿木匠 網站:https://blog.csdn.net/jeffli1993 個人簽名:打算起手不凡寫出鴻篇巨作的人,往往堅持不了完成第一章節。 交流 Q
靜默安裝與智慧安裝:Android 自動化安裝的兩種思路
前言在 Android 裝置管理或企業應用場景中,常會需要安裝或卸載 APK。本文整理兩種常見做法:需要 Root 權限的靜默安裝,以及依靠無障礙服務的智慧安裝。前者完全
Android 圖像繪製(七)ClipRect 局部繪圖與切割原圖總結
雜語:看了很多工程師都有寫部落格的習慣,看來我也得練練,不管寫得好不好,學到點東西就把體會寫寫。 內容解說 這幾天開始學遊戲地圖製作,今天小小心地總結一下 Canvas