2015-09-03 72 views
-2

我想将图库从图库设置为ImageView并保存。所以当我关闭应用程序并再次打开时,ImageView中的图像应该是我从图库中选择的图像。 你可以给我如何做到这一点的示例代码?我是Android开发新手。在图库中设置图像并保存图像?

+1

问题要求我们推荐或找到一本书,工具,软件库,**教程**或其他非现场资源,因为它们倾向于吸引自以为是的答案和垃圾邮件,所以不适合堆栈溢出。相反,请描述问题以及到目前为止解决问题所做的工作。 – Emil

回答

0

你mainactivity:

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

试试这个代码

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; 
} 

}

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

+0

我会试试你的代码 – Paul

+0

嘿..它适合你吗? – Meenal

+0

如何将其保存在外部存储中? – Paul