標籤:android style blog http io os ar java for
通過拍照或者從相簿裡選擇圖片通過壓縮並上傳時很多應用的常用功能,記錄一下實現過程
一:建立個臨時檔案夾用於儲存壓縮後需要上傳的圖片
/** * path:存放圖片目錄路徑 */private String path = Environment.getExternalStorageDirectory().getPath() + "/XXX/";/** * saveCatalog:儲存檔案目錄 */private File saveCatalog;/** * saveFile:儲存的檔案 */private File saveFile; public String createOrGetFilePath(String fileName, Context mContext) {saveCatalog = new File(path);if (!saveCatalog.exists()) {saveCatalog.mkdirs();}saveFile = new File(saveCatalog, fileName);try {saveFile.createNewFile();} catch (IOException e) {Toast.makeText(mContext, "建立檔案失敗,請檢查SD是否有足夠空間", Toast.LENGTH_SHORT).show();e.printStackTrace();}return saveFile.getAbsolutePath();}
二:通過對話方塊選擇獲得圖片方式(拍照或者相簿) <string-array name="get_image_way">
<item >拍照</item> <item >相簿</item> </string-array>
private String[] image;image = getResources().getStringArray(R.array.get_image_way);/** * TODO 通過拍照或者圖冊獲得照片 * * @author {author wangxiaohong} */private void selectImage() {// TODO Auto-generated method stubString state = Environment.getExternalStorageState();if (!state.equals(Environment.MEDIA_MOUNTED)) {Util.showToast(this, getResources().getString(R.string.check_sd)); //檢查SD卡是否可用return;}AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setTitle(R.string.pick_image).setItems(image,new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {if (image[which].equals(getString(R.string.my_data_image_way_photo))) {getImageByPhoto();} else {getImageByGallery();}}});builder.create().show();}
private void getImageByGallery() { Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);intent.setType("image/*");startActivityForResult(intent, IMAGE_RESULT);}
public String getPath(String carId, String fileName, Context mContext) {File saveCatalog = new File(Constant.CACHE, carId);// saveCatalog = new File(path);if (!saveCatalog.exists()) {saveCatalog.mkdirs();}saveFile = new File(saveCatalog, fileName);try {saveFile.createNewFile();} catch (IOException e) {Toast.makeText(mContext, "建立檔案失敗,請檢查SD是否有足夠空間", Toast.LENGTH_SHORT).show();e.printStackTrace();}return saveFile.getAbsolutePath();}
private void getImageByPhoto() {
public static final String CACHE = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/pinchebang/";
path = util.getPath(user.getCar().getCarId() + "", mPhotoName, PersonalInfoActivity.this);imageUri = Uri.fromFile(new File(path));Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);startActivityForResult(intent, CAMERA_RESULT);}
三:在onActivityResult中得到的圖片做壓縮處理
@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {// TODO Auto-generated method stubsuper.onActivityResult(requestCode, resultCode, data);if (resultCode != Activity.RESULT_OK) return;Bitmap bitmap = null;if (requestCode == CAMERA_RESULT) {bitmap = util.getSmallBitmap(PersonalInfoActivity.this, path);boolean flag = util.save(PersonalInfoActivity.this, path, bitmap);} else if (requestCode == IMAGE_RESULT) {Uri selectedImage = data.getData();path = util.getImagePath(PersonalInfoActivity.this, selectedImage);bitmap = util.getSmallBitmap(PersonalInfoActivity.this, path);String pcbPathString = util.getPath(user.getCar().getCarId() + "", mPhotoName,PersonalInfoActivity.this);;util.save(PersonalInfoActivity.this, pcbPathString, bitmap);path = pcbPathString;}if (null != bitmap) {mypicture.setImageBitmap(bitmap);HttpUtil.uploadFile(PersonalInfoActivity.this, path, "userImg",Constant.URL_VERIFY_DRIVER);// MemoryCache memoryCache = new MemoryCache();// memoryCache.put(url, bitmap);}}
上面對應的壓縮方法
/** * TODO filePath:圖片路徑 * * @author {author wangxiaohong} */public Bitmap getSmallBitmap(Context mContext, String filePath) {DisplayMetrics dm;dm = new DisplayMetrics();((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(dm);final BitmapFactory.Options options = new BitmapFactory.Options();options.inJustDecodeBounds = true;BitmapFactory.decodeFile(filePath, options);// Calculate inSampleSizeoptions.inSampleSize = calculateInSampleSize(options, dm.widthPixels, dm.heightPixels);// Decode bitmap with inSampleSize setoptions.inJustDecodeBounds = false;return BitmapFactory.decodeFile(filePath, options);}public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {// Raw height and width of imagefinal int height = options.outHeight;final int width = options.outWidth;int inSampleSize = 1;if (height > reqHeight || width > reqWidth) {// Calculate ratios of height and width to requested height and// widthfinal int heightRatio = Math.round((float) height / (float) reqHeight);final int widthRatio = Math.round((float) width / (float) reqWidth);// Choose the smallest ratio as inSampleSize value, this will// guarantee// a final image with both dimensions larger than or equal to the// requested height and width.inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;}return inSampleSize;}/** * TODO 儲存並壓縮圖片 將bitmap 儲存 到 path 路徑的檔案裡 * * @author {author wangxiaohong} */public boolean save(Context mContext, String path, Bitmap bitmap) {DisplayMetrics dm;dm = new DisplayMetrics();((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(dm);if (path != null) {try {// FileCache fileCache = new FileCache(mContext);// File f = fileCache.getFile(url);File f = new File(path);FileOutputStream fos = new FileOutputStream(f);bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos);saveMyBitmap(bitmap);return true;} catch (Exception e) {return false;}} else {return false;}}private void saveMyBitmap(Bitmap bm) {FileOutputStream fOut = null;try {fOut = new FileOutputStream(saveFile);} catch (FileNotFoundException e) {e.printStackTrace();}bm.compress(Bitmap.CompressFormat.JPEG, 70, fOut);try {fOut.flush();} catch (IOException e) {e.printStackTrace();}try {fOut.close();} catch (IOException e) {e.printStackTrace();}}public String getPath(String carId, String fileName, Context mContext) {File saveCatalog = new File(Constant.CACHE, carId);// saveCatalog = new File(path);if (!saveCatalog.exists()) {saveCatalog.mkdirs();}saveFile = new File(saveCatalog, fileName);try {saveFile.createNewFile();} catch (IOException e) {Toast.makeText(mContext, "建立檔案失敗,請檢查SD是否有足夠空間", Toast.LENGTH_SHORT).show();e.printStackTrace();}return saveFile.getAbsolutePath();}/** * TODO 獲得相簿選擇圖片的圖片路徑 * * @author {author wangxiaohong} */public String getImagePath(Context mContext, Uri contentUri) {String[] proj = { MediaStore.Images.Media.DATA };Cursor cursor = mContext.getContentResolver().query(contentUri, proj, null, null, null);int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);cursor.moveToFirst();String ImagePath = cursor.getString(column_index);cursor.close();return ImagePath;}
四:上傳
public static void uploadFile(Context mContext, String path, String modelValue, String url) {new PhotoUploadAsyncTask(mContext).execute(path, modelValue, url);}class PhotoUploadAsyncTask extends AsyncTask<String, Integer, String> {// private String url = "http://192.168.83.213/receive_file.php";private Context context;public PhotoUploadAsyncTask(Context context) {this.context = context;}@Overrideprotected void onPreExecute() {}@SuppressWarnings("deprecation")@Overrideprotected String doInBackground(String... params) {// 儲存需上傳檔案資訊MultipartEntityBuilder entitys = MultipartEntityBuilder.create();entitys.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);entitys.setCharset(Charset.forName(HTTP.UTF_8));File file = new File(params[0]);entitys.addPart("image", new FileBody(file));entitys.addTextBody("model", params[1]);HttpEntity httpEntity = entitys.build();return HttpUtil.uploadFileWithpost(params[2], context, httpEntity);}@Overrideprotected void onProgressUpdate(Integer... progress) {}@Overrideprotected void onPostExecute(String result) {Toast.makeText(context, result, Toast.LENGTH_SHORT).show();}}/** * 用於檔案上傳 * * @param url * @param mContext * @param entity * @return */@SuppressWarnings("deprecation")public static String uploadFileWithpost(String url, Context mContext, HttpEntity entity) {Util.printLog("開始上傳");try {setTimeout();httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);// 設定連線逾時時間// httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,// 5000);HttpPost upPost = new HttpPost(url);upPost.setEntity(entity);HttpResponse httpResponse = httpClient.execute(upPost, httpContext);if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {return mContext.getString(R.string.upload_success);}} catch (Exception e) {Util.printLog("上傳報錯");e.printStackTrace();}// finally {// if (httpClient != null && httpClient.getConnectionManager() != null)// {// httpClient.getConnectionManager().shutdown();// }// }Util.printLog("上傳成功");return mContext.getString(R.string.upload_fail);}
android 拍照或者圖庫選擇 壓縮後 圖片 上傳