将图像存储到内部存储

时间:2016-07-22 07:04:42

标签: android storage internal

我想将我的图片存储到内部存储空间,我搜索了google和stackoverflow但是无法完成它,这是我的代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    imageView = (ImageView) findViewById(R.id.ss);
    tv = (TextView) findViewById(R.id.tv);
   // Firebase.setAndroidContext(this);
    //Firebase ref = new Firebase(FIREBASE_URL);

    Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i, RESULT_LOAD_IMAGE);
}



protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data)
    {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        bitmap = BitmapFactory.decodeResource(getResources(),
                RESULT_LOAD_IMAGE);

        // Find the SD Card path
        File filepath = Environment.getExternalStorageDirectory();

        // Create a new folder in SD Card
        File dir = new File(filepath.getAbsolutePath()
                + "/Save Image Tutorial/");
        dir.mkdirs();

        // Create a name for the saved image
        File file = new File(dir, "myimage.png");

        // Show a toast message on successful save
        Toast.makeText(MainActivity.this, "Image Saved to SD Card",
                Toast.LENGTH_SHORT).show();
        try {

            output = new FileOutputStream(file);

            // Compress into png format image from 0% - 100%
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
            output.flush();
            output.close();
        }

        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

       // drawView.load_pic(picturePath);
    }
}

我想从图库中获取图像并将其存储到内部存储中,但在此代码中,它只保存目录中文件的名称。如果有人能帮我解决这个问题。

3 个答案:

答案 0 :(得分:0)

您正在外部存储上写图像文件

File filepath = Environment.getExternalStorageDirectory();

因此请检查您是否在Android清单中提及了在SD卡上写入数据的适当权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

并从选定路径获取位图

Bitmap bitmap = BitmapFactory.decodeFile(picturePath);

而不是

bitmap = BitmapFactory.decodeResource(getResources(),
            RESULT_LOAD_IMAGE);

RESULT_LOAD_IMAGE是请求代码而不是所选图像的资源ID

答案 1 :(得分:0)

您可以使用FileOutputStream存储您的位图。从图库获取位图后,FileOutputStream out = null; try { out = new FileOutputStream("fileName"); //Enter the desired filename bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (Exception e) { e.printStackTrace(); } }

答案 2 :(得分:0)

OnChoose代码

        chooseimage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {



            if (Build.VERSION.SDK_INT >= 23){

                boolean result= Utility.checkPermission(getActivity());

                if(result) {
                    galleryIntent();
                }

            }

            else {
                Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                // Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery.
                startActivityForResult(i,LOAD_IMAGE_RESULTS); //LOAD_IMAGE_RESULTS
            }




        }
    });

还添加了运行时权限并在所需位置设置图片

 public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (Build.VERSION.SDK_INT >= 23) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == LOAD_IMAGE_RESULTS) {
                onSelectFromGalleryResult(data);

            }
        }
    }
    else {



                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(data.getData())) {

                    Bitmap bitmap = null;
                    Uri selectedImage = data.getData();
                    String wholeID = DocumentsContract.getDocumentId(selectedImage);

                    // Split at colon, use second item in the array
                    String id = wholeID.split(":")[1];

                    String[] column = {MediaStore.Images.Media.DATA};

                    // where id is equal to
                    String sel = MediaStore.Images.Media._ID + "=?";

                    Cursor cursor = getActivity().getContentResolver().
                            query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                    column, sel, new String[]{id}, null);

                    String filePath = "";

                    int columnIndex = cursor.getColumnIndex(column[0]);

                    if (cursor.moveToFirst()) {
                        //filePath = cursor.getString(columnIndex);
                        mPath = cursor.getString(columnIndex);
                    }


                    cursor.close();

                }
                else {
                    if (requestCode == LOAD_IMAGE_RESULTS && resultCode == getActivity().RESULT_OK && data != null) {
                        // Let's read picked image data - its URI
                        Uri pickedImage = data.getData();
                        // Let's read picked image path using content resolver
                        String[] filePath = {MediaStore.Images.Media.DATA};
                        Cursor cursor = getActivity().getContentResolver().query(pickedImage, filePath, null, null, null);
                        cursor.moveToFirst();
                        mPath = cursor.getString(cursor.getColumnIndex(filePath[0]));
                        //edAttach.setText(mPath.toString()); path set anywhere
                        cursor.close();
                    }

                }
    }
}




private void onSelectFromGalleryResult(Intent data) {

    Bitmap bitmap=null;
    if (data != null) {
        try {
            bitmap= MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
        } catch (IOException e) {
            e.printStackTrace();
        }
ivprofile.setImageBitmap(bm);
    }



    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(data.getData())) {
        Uri selectedImage = data.getData();
        String wholeID = DocumentsContract.getDocumentId(selectedImage);

        // Split at colon, use second item in the array
        String id = wholeID.split(":")[1];

        String[] column = {MediaStore.Images.Media.DATA};

        // where id is equal to
        String sel = MediaStore.Images.Media._ID + "=?";

        Cursor cursor = getActivity().getContentResolver().
                query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        column, sel, new String[]{id}, null);

        String filePath = "";

        int columnIndex = cursor.getColumnIndex(column[0]);

        if (cursor.moveToFirst()) {
            //filePath = cursor.getString(columnIndex);
            mPath = cursor.getString(columnIndex);
            //edAttach.setText(mPath); path set anywhere


        }
        cursor.close();
    }
    else {
        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = getActivity().getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        mPath = cursor.getString(columnIndex).toString();
        System.out.println("picturePath" + mPath);
        if (!mPath.equalsIgnoreCase(null)) {
            edAttach.setText(mPath);
        }
        cursor.close();


    }


    // Your Image Copy on Your desired location

  if(!mPath.equalsIgnoreCase(""))
        {
            File filepath = Environment.getExternalStorageDirectory();

            // Create a new folder in SD Card
            File dir = new File(filepath.getAbsolutePath()
                    + "/"+"Save Image Tutorial"+"/");
            dir.mkdirs();

            // Create a name for the saved image
            File file = new File(dir, "myImage.png");

            // Show a toast message on successful save


            try {

                FileOutputStream output = new FileOutputStream(file);

                // Compress into png format image from 0% - 100%
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
                output.flush();
                output.close();


                Toast.makeText(getActivity(), "Image Saved to SD Card",
                        Toast.LENGTH_SHORT).show();
            }

            catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }


}

public boolean hasPermissionInManifest(Context context, String permissionName) {
    final String packageName = context.getPackageName();
    try {
        final PackageInfo packageInfo = context.getPackageManager()
                .getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
        final String[] declaredPermisisons = packageInfo.requestedPermissions;
        if (declaredPermisisons != null && declaredPermisisons.length > 0) {
            for (String p : declaredPermisisons) {
                if (p.equals(permissionName)) {
                    return true;
                }
            }
        }
    } catch (PackageManager.NameNotFoundException e) {

    }
    return false;
}


 public static boolean isMediaDocument(Uri uri)
{
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

private void galleryIntent()
{
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);//
    startActivityForResult(Intent.createChooser(intent, "Select File"),LOAD_IMAGE_RESULTS);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {


                galleryIntent();

            } else {
                //code for deny
            }
            break;
    }
}

或权限在mainfiest.xml中

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<强> Utility.java

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

public class Utility {
    public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public static boolean checkPermission(final Context context)
    {
        int currentAPIVersion = Build.VERSION.SDK_INT;
        if(currentAPIVersion>= Build.VERSION_CODES.M)
        {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
                    alertBuilder.setCancelable(true);
                    alertBuilder.setTitle("Permission necessary");
                    alertBuilder.setMessage("External storage permission is necessary");
                    alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                        }
                    });
                    AlertDialog alert = alertBuilder.create();
                    alert.show();
                } else {
                    ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                }
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }
}