android 照相或選擇圖片最新整理,處理2.1SDK相容問題。

來源:互聯網
上載者:User

經過最近項目曆練不同手機型號已經SDK版本以後,發現上次寫的名為:android2.3選擇相簿圖片或者調用系統照相 的文章中,存在一個bug,就是在2.1的索尼手機上使用不了,並且無法擷取到圖片原生大小。下面做下最近的測試成功的記錄,主要以調用相簿和,系統攝像機為主:

/** * Show Check Image Dialog */private void showheckImageDialog() {final CharSequence[] items = { getResources().getString(R.string.photo_manager_check_cameras),getResources().getString(R.string.photo_manager_check_image) };Builder builder = new AlertDialog.Builder(this);builder.setTitle(R.string.photo_manager_check_dialog_title).setItems(items, this);builder.create().show();}@Overridepublic void onClick(DialogInterface dialog, int which) {if (which == 0) { // Camerastry {// get image file save pathtemporaryPhotoPath = getImageFilePath();// user sdk camerasIntent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);File captureFile = new File(temporaryPhotoPath);this.captureUri = Uri.fromFile(captureFile);intent.putExtra(MediaStore.EXTRA_OUTPUT, captureUri);startActivityForResult(intent, CAMERAMAN_IMAGE);} catch (Exception e) {Logging.e("error", e.getMessage());}} else {Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);getImage.addCategory(Intent.CATEGORY_OPENABLE);getImage.setType("image/*");startActivityForResult(Intent.createChooser(getImage, getString(R.string.photo_select_title)), SELECT_IMAGE);}}

說明一下,上面 temporaryPhotoPath 是圖片需要儲存的路徑。

下面是回調方法擷取圖片路徑的方法,需要注意一下的是 不能用回調方法的 Intent 參數擷取image,因為這樣擷取的是被系統縮小的圖片對象,而不是圖片的原生映像。

@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {Bitmap bitmap = null;String parth = null;if (data != null) {// get file pathparth = FileManager.getImagePathByIntent(this, data);}// copy fileif (StringUtil.isExistsData(parth) && !parth.equals(this.temporaryPhotoPath)) {// get file save pathif (!StringUtil.isExistsData(this.temporaryPhotoPath)) {this.temporaryPhotoPath = getImageFilePath();}FileManager.copyFile(parth, this.temporaryPhotoPath);}// get imageif (StringUtil.isExistsData(temporaryPhotoPath)) {bitmap = FileManager.converntBitmapSize(temporaryPhotoPath, 960);this.temporaryPhotoPath = null;}

上面的代碼中copyFile ()是將圖片複製到我們指定的目錄, 下面是擷取圖片的路徑的方法和複製檔案的方法:

/** * Get Image By Intent *  * @param data * @return */public static String getImagePathByIntent(Activity activity, Intent data) {String path = null;Cursor cursor = null;try {Uri originalUri = data.getData();path = originalUri.toString();String[] proj = { MediaStore.Images.Media.DATA };cursor = activity.managedQuery(originalUri, proj, null, null, null);if (cursor != null) {int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);cursor.moveToFirst();path = cursor.getString(column_index);}path = path.substring(path.indexOf("/sdcard"), path.length());} catch (Exception e) {Logging.e("getImageByIntent error", e.getMessage());} finally {if (cursor != null) cursor.close();}return path;}

/** * copy file *  * @param sourcePath * @param newPath * @return */public static boolean copyFile(String sourcePath, String newPath) {boolean isSuccess = false;try {File sourceFile = new File(sourcePath);if (!sourceFile.exists()) {return isSuccess;}// delete already fileFile newFile = new File(newPath);if (newFile.exists()) {newFile.delete();}// copy fileisSuccess = sourceFile.renameTo(newFile);} catch (Exception e) {Logging.e("copyFile error", e.getMessage());}return isSuccess;}

下面是轉換圖片大小並儲存的方法:

/** * convert image size *  * @param imagePath *            String image file path * @param width *            Int new image max width * @param height *            Int new image max height * @return */public static Bitmap converntBitmapSize(String imagePath, int maxSize) {Bitmap bitmap = null;int defaultMaxSize = 960;try {if (maxSize > 0) {defaultMaxSize = maxSize;}File imageFile = new File(imagePath);if (imageFile.exists()) {BitmapFactory.Options options = new BitmapFactory.Options();options.inJustDecodeBounds = true;BitmapFactory.decodeFile(imagePath, options);// the resource image max sizeint sourceMaxSize = Math.max(options.outWidth, options.outHeight);if (sourceMaxSize < 1) {return null;}int scale = sourceMaxSize / defaultMaxSize;options.inJustDecodeBounds = false;options.inSampleSize = scale;// first narrow imagebitmap = BitmapFactory.decodeFile(imagePath, options);int newMaxSize = Math.max(bitmap.getWidth(), bitmap.getHeight());if (newMaxSize > defaultMaxSize) {// second narrow imagefloat newSize = (float) defaultMaxSize / (float) newMaxSize;Matrix matrix = new Matrix();matrix.postScale(newSize, newSize);bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);matrix = null;}saveImage(bitmap, imagePath);}} catch (Exception e) {Logging.e("converntBitmapSize", e.getMessage());}return bitmap;}

經過測試,目前沒有遇到無法使用的情況。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.