Android: Saving an image to directory

≯℡__Kan透↙ 提交于 2019-12-08 11:08:37

问题


I'm trying to save a bitmap to my directory but haven't a little trouble.

What my applications does is:

1.Opens the inbuilt camera application by an Intent.

public void openCamera() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(Environment.getExternalStorageDirectory()+ File.separator + "image.jpg");
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }

2.It then stores the picture intent into 'REQUEST_IMAGE_CAPTURE' and saves the image into a temp directory.

startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);

3.Which is then converted into a bitmap and loaded from the tmp directory into an image view

 protected void onActivityResult(int requestCode, int resultCode, Intent data){
        //Check that request code matches ours:
        if (requestCode == REQUEST_IMAGE_CAPTURE){
            //Get our saved file into a bitmap object:
            File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
            Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
            imageView.setImageBitmap(image);
        }
    }

Now, how do i save the bitmap which in the imageview into the picture directory?

I have inputted the permissions into my manifest

<uses-feature android:name="android.hardware.camera"
    android:required="true" />
...
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
...
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> 

回答1:


use bitmap.compress in order to direct the bitmap into an OutputStream.

for example:

FileOutputStream fo = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fo); // bmp is your Bitmap 



回答2:


   private void saveImage(Bitmap bmp, String filePath){

    File file = new File(filePath);
    FileOutputStream fo = null;
    try {
        boolean result = file.createNewFile(); // true if created, false if exists or failed
        fo = new FileOutputStream(file);
        bmp.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY_PERCENT, fo);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (fo != null) {
            try {
                fo.flush();
                fo.close();
            } catch (Exception ignored) {

            }
        }
    }
}

Note that filePath is directory + filename e.g. /sdcard/iamges/1.jpg



来源:https://stackoverflow.com/questions/29878141/android-saving-an-image-to-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!