将图像保存在特定的SD卡文件夹中

时间:2015-02-21 07:19:28

标签: java android image camera

文件已创建并显示但默认存储在dcim文件夹

public class MainActivity extends Activity {

    Button camera;
    ImageView mImageView;
    static final int REQUEST_TAKE_PHOTO = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        camera=(Button)findViewById(R.id.captureButton);
        mImageView= (ImageView) findViewById(R.id.imageView);

        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dispatchTakePictureIntent();

            }
        });
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {

            }
            if (photoFile != null) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(photoFile));

            }
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }

    String mCurrentPhotoPath;

    private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,
                ".jpg",
                storageDir
        );
        mCurrentPhotoPath = "file:" + image.getAbsolutePath();
        return image;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            mImageView.setImageBitmap(imageBitmap);
        }

     }

}

为什么还没有创建storageDir文件夹?我该如何创建文件夹?并在特定文件夹中存储图像给我一些代码,这些代码可以帮助我感谢andvace

1 个答案:

答案 0 :(得分:0)

这对我有用。

File myDir=new File("/sdcard/folder_you_want_to_save_in");
myDir.mkdirs();

String fname = "JPEG_"+ timeStamp +".jpg";

File file = new File (myDir, fname);

if (file.exists ()) file.delete (); 

try {
    FileOutputStream out = new FileOutputStream(file);
    finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
    out.flush();
    out.close();

} catch (Exception e) {
    e.printStackTrace();
}