從相簿擷取圖片及調用相機拍照擷取圖片,最後上傳圖片到伺服器,相機上傳圖片
調用相機拍照擷取圖片:跳轉到到拍照介面: Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//下面這句指定調用相機拍照後的照片儲存的路徑mSzImageFileName = Long.toString(System.currentTimeMillis()) + ".png";takeIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(Environment.getExternalStorageDirectory(), mSzImageFileName)));startActivityForResult(takeIntent, REQUEST_TAKE_PHOTO); 從相簿擷取圖片: 從相簿選擇圖片: Intent pickIntent = new Intent(Intent.ACTION_PICK, null);// 如果要限制上傳到伺服器的圖片類型時可以直接寫如:image/jpeg 、 image/png等的類型pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");startActivityForResult(pickIntent, REQUEST_PICK_PHOTO); 從相簿返回一張圖片或者拍照返回一張圖片:監聽返回結果:@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {switch (requestCode) {case REQUEST_PICK_PHOTO:// 直接從相簿擷取try {startPhotoZoom(data.getData());//跳轉到介面} catch (NullPointerException e) {e.printStackTrace();// 使用者點擊取消操作}break;case REQUEST_TAKE_PHOTO:// 調用相機拍照mHandler.postDelayed(new Runnable() {@Overridepublic void run() {File temp = new File(Environment.getExternalStorageDirectory(), mSzImageFileName);if (temp.exists()) {startPhotoZoom(Uri.fromFile(temp));//跳轉到介面}}}, 1000);break;case REQUEST_CUT_PHOTO:// 取得裁剪後的圖片if (data != null) {setPicToView(data);//儲存和上傳圖片}break;} super.onActivityResult(requestCode, resultCode, data);} 返回圖片後進行裁剪:裁剪圖片:/*** 裁剪圖片方法實現*/private void startPhotoZoom(Uri uri) {LogUtil.e("PersonalInformationActivity", "onActivityResult uri" + uri);if (uri != null) {Intent intent = new Intent("com.android.camera.action.CROP");intent.setDataAndType(uri, "image/*");// 下面這個crop=true是設定在開啟的Intent中設定顯示的VIEW可裁剪intent.putExtra("crop", "true");// aspectX aspectY 是寬高的比例intent.putExtra("aspectX", 1);intent.putExtra("aspectY", 1);// outputX outputY 是裁剪圖片寬高intent.putExtra("outputX", 300);intent.putExtra("outputY", 300);intent.putExtra("return-data", true);startActivityForResult(intent, REQUEST_CUT_PHOTO);}} 裁剪後儲存和上傳圖片:/*** 儲存裁剪之後的圖片資料** @param picdata*/private void setPicToView(Intent picdata) {Bundle extras = picdata.getExtras();if (extras != null) {// 取得SDCard圖片路徑做顯示Bitmap photo = extras.getParcelable("data");mSzImageFileName = Long.toString(System.currentTimeMillis()) + ".png";mImgUrlPath = Environment.getExternalStorageDirectory() + File.separator + "cut_image" + File.separator + mSzImageFileName;try {NetUtil.saveBitmapToFile(photo, mImgUrlPath);} catch (IOException e) {e.printStackTrace();} // 新線程後台上傳服務端new Thread(uploadImageRunnable).start();}} 上傳圖片的線程:Runnable uploadImageRunnable = new Runnable() {@Overridepublic void run() {Map<String, String> params = new HashMap<>();params.put("mid", mSzId);//上傳參數Map<String, File> files = new HashMap<>();files.put("myUpload", new File(mImgUrlPath));//上傳檔案路徑try {String json = NetUtil.uploadFile(Constants.URL_EDIT_IMG, params, files);//json為伺服器返回的資料,可自己解析(如json解析)取得想要的資料}}} catch (IOException e) {e.printStackTrace();}}}; 儲存圖片和上傳圖片的工具類NetUtil :public class NetUtil {//上傳圖片到伺服器public static String uploadFile(String url, Map<String, String> params, Map<String, File> files)throws IOException {String tempStr = null;String BOUNDARY = java.util.UUID.randomUUID().toString();String PREFIX = "--", LINEND = "\r\n";String MULTIPART_FROM_DATA = "multipart/form-data";String CHARSET = "UTF-8";HttpURLConnection conn = null;try {URL uri = new URL(url);conn = (HttpURLConnection) uri.openConnection();conn.setReadTimeout(10 * 1000); // 緩衝的最長時間conn.setDoInput(true);// 允許輸入conn.setDoOutput(true);// 允許輸出conn.setUseCaches(false); // 不允許使用緩衝conn.setRequestMethod("POST");conn.setRequestProperty("connection", "keep-alive");conn.setRequestProperty("Charsert", "UTF-8");conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);// 首先組拼文本類型的參數StringBuilder sb = new StringBuilder();for (Map.Entry<String, String> entry : params.entrySet()) {sb.append(PREFIX);sb.append(BOUNDARY);sb.append(LINEND);sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);sb.append("Content-Transfer-Encoding: 8bit" + LINEND);sb.append(LINEND);sb.append(entry.getValue());sb.append(LINEND);}LogUtil.e("NetUtil", "uploadFile sb:" + sb.toString());DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());outStream.write(sb.toString().getBytes());// 傳送檔案資料if (files != null)for (Map.Entry<String, File> file : files.entrySet()) {StringBuilder sb1 = new StringBuilder();sb1.append(PREFIX);sb1.append(BOUNDARY);sb1.append(LINEND);sb1.append("Content-Disposition: form-data; name="+file.getKey()+"; filename=\""+ file.getValue() + "\"" + LINEND);sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);sb1.append(LINEND);LogUtil.e("NetUtil", "uploadFile sb1:" + sb1.toString());outStream.write(sb1.toString().getBytes());InputStream is = new FileInputStream(file.getValue());byte[] buffer = new byte[1024];int len = 0;while ((len = is.read(buffer)) != -1) {outStream.write(buffer, 0, len);}is.close();outStream.write(LINEND.getBytes());}// 請求結束標誌byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();outStream.write(end_data);outStream.flush();outStream.close();StringBuilder sb2 = new StringBuilder();BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), CHARSET));String inputLine;while ((inputLine = in.readLine()) != null) {sb2.append(inputLine);}in.close();tempStr = sb2.toString();} catch (Exception e) {} finally {if (conn != null) {conn.disconnect();}}return tempStr;} /*** Save Bitmap to a file.儲存圖片到SD卡。** @param bitmap* @return error message if the saving is failed. null if the saving is* successful.* @throws IOException*/public static void saveBitmapToFile(Bitmap bitmap, String _file)throws IOException {BufferedOutputStream os = null;try {File file = new File(_file);int end = _file.lastIndexOf(File.separator);String _filePath = _file.substring(0, end);File filePath = new File(_filePath);if (!filePath.exists()) {filePath.mkdirs();}file.createNewFile();os = new BufferedOutputStream(new FileOutputStream(file));bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);} finally {if (os != null) {try {os.close();} catch (IOException e) {}}}}}