在图库视图中设置图像并保存?

时间:2015-09-03 06:03:35

标签: android android-imageview

我想将图像从图库设置为ImageView并保存。因此,当我关闭应用程序并再次打开它时,ImageView中的图像应该是我从图库中选择的图像。 你能给我一些关于如何做的示例代码吗?我是Android开发的新手。

2 个答案:

答案 0 :(得分:1)

您的主要活动:

  public class MainActivity extends Activity {
        private static int RESULT_LOAD_IMG = 1;
        String imgDecodableString;
     
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
     
        public void loadImagefromGallery(View view) {
            // Create intent to Open Image applications like Gallery, Google Photos
            Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            // Start the Intent
            startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
        }
     
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            try {
                // When an Image is picked
                if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                        && null != data) {
                    // Get the Image from data
     
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = { MediaStore.Images.Media.DATA };
     
                    // Get the cursor
                    Cursor cursor = getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);
                    // Move to first row
                    cursor.moveToFirst();
     
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    imgDecodableString = cursor.getString(columnIndex);
                    cursor.close();
                    ImageView imgView = (ImageView) findViewById(R.id.imgView);
                    // Set the Image in ImageView after decoding the String
                    imgView.setImageBitmap(BitmapFactory
                            .decodeFile(imgDecodableString));
     
                } else {
                    Toast.makeText(this, "You haven't picked Image",
                            Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {
                Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                        .show();
            }
     
        }
     
    }

你的Xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" >
    </ImageView>

    <Button
        android:id="@+id/buttonLoadPicture"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="0"
        android:onClick="loadImagefromGallery"
        android:text="Load Picture" >
    </Button>

</LinearLayout>

清单许可:

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

答案 1 :(得分:1)

试试此代码

public class MainActivity extends Activity {
private ImageView imageView;
private int RESULT_LOAD_IMAGE = 123;
private String PREFS_NAME = "image";
private Context mContext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    try {
        mContext = this;
        imageView = (ImageView) findViewById(R.id.imageView1);
        String path = getPreference(mContext, "imagePath");

        if (path == null || path.length() == 0 || path.equalsIgnoreCase("")) {
            Intent i = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, RESULT_LOAD_IMAGE);

        } else {
            imageView.setImageBitmap(getScaledBitmap(path, 800, 800));
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        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();
            setPreference(mContext, picturePath, "imagePath");
            imageView
                    .setImageBitmap(getScaledBitmap(picturePath, 800, 800));
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

private Bitmap getScaledBitmap(String picturePath, int width, int height) {
    BitmapFactory.Options sizeOptions = null;
    try {
        sizeOptions = new BitmapFactory.Options();
        sizeOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(picturePath, sizeOptions);

        int inSampleSize = calculateInSampleSize(sizeOptions, width, height);

        sizeOptions.inJustDecodeBounds = false;
        sizeOptions.inSampleSize = inSampleSize;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return BitmapFactory.decodeFile(picturePath, sizeOptions);
}

private int calculateInSampleSize(BitmapFactory.Options options,
        int reqWidth, int reqHeight) {
    int inSampleSize = 0;
    try {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            // Calculate ratios of height and width to requested height and
            // width
            final 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;
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return inSampleSize;
}

boolean setPreference(Context c, String value, String key) {
    SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
    settings = c.getSharedPreferences(PREFS_NAME, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString(key, value);
    return editor.commit();
}

String getPreference(Context c, String key) {
    SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
    settings = c.getSharedPreferences(PREFS_NAME, 0);
    String value = settings.getString(key, "");
    return value;
}

}

还在清单中添加读取外部存储的权限。 我使用共享首选项来保存所选图像的路径。您还可以将所选图像保存在单独的文件夹中,并优先保存该文件夹路径。