从库中创建图像并创建一个文件夹

时间:2015-09-18 06:41:36

标签: android

这个简单的代码要求用户从图库中选择图像

  private void openGallery() {
      Intent gallery = 
         new Intent(Intent.ACTION_PICK, 
         android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
      startActivityForResult(gallery, PICK_IMAGE);
   }

   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
         Uri imageUri = data.getData();
         imageView.setImageURI(imageUri);
      }
   }
}

我的问题:我看到许多代码或应用在用户上传图片时会创建一个文件夹。我应该这样做吗?以及如何使用上面的代码创建文件夹

1 个答案:

答案 0 :(得分:2)

动态检查以下代码以查找创建文件夹。

String root = Environment.getExternalStorageDirectory()
                    .toString();
            new File(root + "/" + Constants.IMAGE_DIRECTORY_NAME + "/"
                    + Constants.SUB_DIRECTORY_NAME).mkdirs();

请为您选择的图库图像创建位图文件,并保存到您自己创建的文件夹中。

File outputfile = new File(root + "/"
                    + Constants.IMAGE_DIRECTORY_NAME + "/"
                    + Constants.SUB_DIRECTORY_NAME + "/", "img_"
                    + dateFormatter.format(new Date()).toString() + ".jpeg");

            OutputStream outStream = null;
            try {                   
                outStream = new FileOutputStream(outputfile);
                bmFrame.compress(Bitmap.CompressFormat.JPEG, 70, outStream);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Log.e(TAG, e.toString());

            } finally {
                try {
                    if (outStream != null) {
                        outStream.flush();
                        outStream.close();
                        bmFrame.recycle();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

        }

在onActivityResult上使用上面的代码

@Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
         Uri imageUri = data.getData();
         imageView.setImageURI(imageUri);

         Bitmap bmFrame = MediaStore.Images.Media.getBitmap(
                    this.getContentResolver(), imageUri);

         //Add above code here.
      }
   }