看板 KnucklesNote
作者 標題 [AndroidStudio] 選取相簿圖片 使用Imgur API上傳
時間 2016-09-09 Fri. 11:23:02
依照這一篇 [AndroidStudio] 建立文章編輯器 - KnucklesNote板 - Disp BBS
建立了編輯器的頁面後,加個上傳圖片的功能
在右上角的選單點選「上傳圖片」後,選擇相簿的圖片
使用 Imgur API 上傳後,取得圖片網址,插入編輯器中
![[圖]](http://i.imgur.com/g3t7HWh.png)
在 editorActivity 加入一個成員變數
用來識別是否從選取圖片頁面回來的 request code
private final int REQUEST_PICK_IMAGE = 1;
在右上角的功能選單加上「插入圖片」的按鈕
點擊後會執行 textInsertImage();
private void textInsertImage(){
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_PICK_IMAGE);
}
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_PICK_IMAGE);
}
加上 onActivityResult() 事件,在選好圖片後,
執行自訂的成員函式 getSelectImage() 處理選取的圖片
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) { return; }
switch(requestCode){
case REQUEST_PICK_IMAGE:
getSelectImage(data); //處理選取圖片的程式 寫在後面
break;
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) { return; }
switch(requestCode){
case REQUEST_PICK_IMAGE:
getSelectImage(data); //處理選取圖片的程式 寫在後面
break;
}
}
加上自訂的成員函式 getSelectImage()
//選擇了要插入的圖片後,在onActivityResult會執行這個
private void getSelectImage(Intent data){
//從 onActivityResult 傳入的data中,取得圖檔路徑
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
if(cursor==null){ return; }
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imagePath = cursor.getString(columnIndex);
cursor.close();
//Log.d("editor","image:"+imagePath);
//使用圖檔路徑產生調整過大小的Bitmap
Bitmap bitmap = getResizedBitmap(imagePath); //程式寫在後面
//將 Bitmap 轉為 base64 字串
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] bitmapData = bos.toByteArray();
String imageBase64 = Base64.encodeToString(bitmapData, Base64.DEFAULT);
//Log.d("editor",imageBase64);
//將圖檔上傳至 Imgur,將取得的圖檔網址插入文字輸入框
imgurUpload(imageBase64); //程式寫在後面
}
取得圖檔的路徑後使用 getResizedBitmap() 產生調整過大小的 Bitmapprivate void getSelectImage(Intent data){
//從 onActivityResult 傳入的data中,取得圖檔路徑
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
if(cursor==null){ return; }
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imagePath = cursor.getString(columnIndex);
cursor.close();
//Log.d("editor","image:"+imagePath);
//使用圖檔路徑產生調整過大小的Bitmap
Bitmap bitmap = getResizedBitmap(imagePath); //程式寫在後面
//將 Bitmap 轉為 base64 字串
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] bitmapData = bos.toByteArray();
String imageBase64 = Base64.encodeToString(bitmapData, Base64.DEFAULT);
//Log.d("editor",imageBase64);
//將圖檔上傳至 Imgur,將取得的圖檔網址插入文字輸入框
imgurUpload(imageBase64); //程式寫在後面
}
將 Bitmap 轉為 base64 字串後,使用 imgurUpload() 上傳
getResizedBitmap() 的程式參考下一篇文章
[AndroidStudio] 將圖檔的寬高縮小 bitmap resize - KnucklesNote板 - Disp BBS
將圖檔上傳至 imgur 的程式為
private void imgurUpload(final String image){ //插入圖片
String urlString = "https://imgur-apiv3.p.mashape.com/3/image/";
String mashapeKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; //設定自己的 Mashape Key
String clientId = "XXXXXXXXXXX"; //設定自己的 Clinet ID
String titleString = ""; //設定圖片的標題
showLoadingDialog("上傳中...");
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("X-Mashape-Key", mashapeKey);
client.addHeader("Authorization", "Client-ID "+clientId);
client.addHeader("Content-Type", "application/x-www-form-urlencoded");
RequestParams params = new RequestParams();
params.put("title", titleString);
params.put("image", image);
client.post(urlString, params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
dismissLoadingDialog();
if (!response.optBoolean("success") || !response.has("data")) {
Log.d("editor", "response: "+response.toString());
return;
}
JSONObject data = response.optJSONObject("data");
//Log.d("editor","link: "+data.optString("link"));
String link = data.optString("link","");
int width = data.optInt("width",0);
int height = data.optInt("height",0);
String bbcode = "[img="+width+"x"+height+"]"+link+"[/img]";
textInsertString(bbcode); //將文字插入輸入框的程式 寫在後面
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable e, JSONObject error) {
dismissLoadingDialog();
//Log.d("editor","error: "+error.toString());
if (error.has("data")) {
JSONObject data = error.optJSONObject("data");
AlertDialog dialog = new AlertDialog.Builder(mContext)
.setTitle("Error: " + statusCode + " " + e.getMessage())
.setMessage(data.optString("error",""))
.setPositiveButton("確定", null)
.create();
dialog.show();
}
}
});
}
String urlString = "https://imgur-apiv3.p.mashape.com/3/image/";
String mashapeKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; //設定自己的 Mashape Key
String clientId = "XXXXXXXXXXX"; //設定自己的 Clinet ID
String titleString = ""; //設定圖片的標題
showLoadingDialog("上傳中...");
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("X-Mashape-Key", mashapeKey);
client.addHeader("Authorization", "Client-ID "+clientId);
client.addHeader("Content-Type", "application/x-www-form-urlencoded");
RequestParams params = new RequestParams();
params.put("title", titleString);
params.put("image", image);
client.post(urlString, params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
dismissLoadingDialog();
if (!response.optBoolean("success") || !response.has("data")) {
Log.d("editor", "response: "+response.toString());
return;
}
JSONObject data = response.optJSONObject("data");
//Log.d("editor","link: "+data.optString("link"));
String link = data.optString("link","");
int width = data.optInt("width",0);
int height = data.optInt("height",0);
String bbcode = "[img="+width+"x"+height+"]"+link+"[/img]";
textInsertString(bbcode); //將文字插入輸入框的程式 寫在後面
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable e, JSONObject error) {
dismissLoadingDialog();
//Log.d("editor","error: "+error.toString());
if (error.has("data")) {
JSONObject data = error.optJSONObject("data");
AlertDialog dialog = new AlertDialog.Builder(mContext)
.setTitle("Error: " + statusCode + " " + e.getMessage())
.setMessage(data.optString("error",""))
.setPositiveButton("確定", null)
.create();
dialog.show();
}
}
});
}
其中 mashapeKey 與 clientId 的取得方法參考這篇
[PHP] 使用 Imgur API 上傳圖片 - KnucklesNote板 - Disp BBS
存取網路資料使用了 AsyncHttpClient 參考這篇
[AndroidStudio] 使用 AsyncHttpClient 存取網路資料 - KnucklesNote板 - Disp BBS
新增將文字插入輸入框的成員函式 textInsertString()
private void textInsertString(String insertString){
int start = mTextEditText.getSelectionStart();
mTextEditText.getText().insert(start, insertString);
}
int start = mTextEditText.getSelectionStart();
mTextEditText.getText().insert(start, insertString);
}
參考:
http://curious-blog.blogspot.tw/2013/06/pick-image-and-upload-to-server-in.html
http://stackoverflow.com/questions/5309190/android-pick-images-from-gallery
--
※ 作者: Knuckles 時間: 2016-09-09 11:23:02
※ 編輯: Knuckles 時間: 2016-09-20 13:10:24
※ 看板: KnucklesNote 文章推薦值: 0 目前人氣: 0 累積人氣: 1074
回列表(←)
分享