title: Android拍照上傳至PHP服務(wù)器并寫入MySql數(shù)據(jù)庫(下)
date: 2016-07-22 15:45:32
tags:
- PHP
- Android
Android實(shí)現(xiàn)
調(diào)用系統(tǒng)相機(jī),拍照:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
getFileUri();
intent.putExtra(MediaStore.EXTRA_OUTPUT, file_uri);
startActivityForResult(intent, CODE_CAMERA);
private void getFileUri() {
image_name = Calendar.getInstance().getTimeInMillis() + ".jpg";
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + image_name);
file_uri = Uri.fromFile(file);
}
在onActivityResult里面接收?qǐng)D片并Base64處理:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CODE_CAMERA && resultCode == RESULT_OK) {
new EncodeImage().execute(); //把bitmap轉(zhuǎn)換成base64字符串
}
}
EncodeImage是一個(gè)AsyncTask牺汤,doInBackground里面從uri里面獲取bitmap诫尽,然后轉(zhuǎn)入輸出流埋泵,最終轉(zhuǎn)換為base64編碼字符串:
@Override
protected Void doInBackground(Void... voids) {
bitmap = BitmapFactory.decodeFile(file_uri.getPath());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
byte[] array = stream.toByteArray();
encoded_string = Base64.encodeToString(array, 0);
bitmap.recycle(); //防止oom
return null;
}
然后就可以上傳到服務(wù)器了:
private void uploadImage() {
HashMap<String, String> map = new HashMap<>();
map.put("encoding_string", encoded_string);
map.put("image_name", image_name);
OkHttpUtils.post()
.url("http:192.168.0.112/phpdemo/uploadimage.php")
.params(map)
.tag(this)
.build()
.execute(new StringCallback() {
@Override
public void onError(Call call, Exception e, int id) {
Log.e("出錯(cuò)了", "錯(cuò)誤信息:" + e.getMessage());
}
@Override
public void onResponse(String response, int id) {
Log.e("成功or失敗", "信息:" + response);
}
});
}
在上傳服務(wù)器過程中车份,遇到兩個(gè)問題拂苹,第一,提示POST Content-Length of ... bytes exceeds the limit of 8388608 bytes
,這個(gè)錯(cuò)誤是因?yàn)閜hp默認(rèn)最大post上傳8M,更改php.ini里面的post_max_size=1000M
就ok了厨剪;第二岂傲,當(dāng)?shù)诙闻恼盏臅r(shí)候會(huì)出現(xiàn)OOM的情況难裆,檢查代碼發(fā)現(xiàn)bitmap沒有recycle。
OVER