从图库中选择图像并保存以备将来使用

Posted

技术标签:

【中文标题】从图库中选择图像并保存以备将来使用【英文标题】:Select Image From gallery and save it for future use 【发布时间】:2012-06-15 10:51:31 【问题描述】:

我正在开发应用程序,我希望用户可以从图库中选择图像,以便他可以在其上应用框架。我成功访问了移动图库,现在我想知道如何保存所选图像以供进一步处理。所选图像将用于在其上应用框架。

【问题讨论】:

【参考方案1】:

给你。

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

    switch(requestCode)  
    case REQ_CODE_PICK_IMAGE:
        if(resultCode == RESULT_OK)  
            Uri selectedImage = imageReturnedIntent.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 filePath = cursor.getString(columnIndex);
            cursor.close();


            Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);

            //Now do whatever processing you want to do on it.
        
    

【讨论】:

【参考方案2】:

使用以下代码从图库中选择图像:

Intent intent=new Intent();
intent.setType=("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE);
/*Declare PICK_IMAGE globally :  private static final int PICK_IMAGE = 1;  */

实际代码从这里开始

protected void onActivityResult(int requestCode, int resultCode, Intent data) 

    switch (requestCode) 
    case PICK_IMAGE:
        if (resultCode == Activity.RESULT_OK) 
            Uri selectedImageUri = data.getData();
            try 
                // OI FILE Manager
                String filemanagerstring = selectedImageUri.getPath();

                // MEDIA GALLERY
                String selectedImagePath = getPath(selectedImageUri);

                if (selectedImagePath != null) 
                    filePath = selectedImagePath;
                 else if (filemanagerstring != null) 
                    filePath = filemanagerstring;
                 else 
                    Toast.makeText(getApplicationContext(), "Unknown path",
                            Toast.LENGTH_LONG).show();
                    Log.e("Bitmap", "Unknown path");
                

                if (filePath != null) 
                    Log.e("file path  ","file path "+filePath);
                    GlobalValues.camefromtw="true";
                    decodeFile(filePath);
                 else 
                    bitmap = null;
                
             catch (Exception e) 
                Toast.makeText(getApplicationContext(), "Internal error",
                        Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
            
        
        break;protected void onActivityResult(int requestCode, int resultCode, Intent data) 

    switch (requestCode) 
    case PICK_IMAGE:
        Log.e("result code","result code"+resultCode+"  result   "+Activity.RESULT_OK);
        if (resultCode == Activity.RESULT_OK) 
            Uri selectedImageUri = data.getData();
            try 
                // OI FILE Manager
                String filemanagerstring = selectedImageUri.getPath();

                // MEDIA GALLERY
                String selectedImagePath = getPath(selectedImageUri);

                if (selectedImagePath != null) 
                    filePath = selectedImagePath;
                 else if (filemanagerstring != null) 
                    filePath = filemanagerstring;
                 else 
                    Toast.makeText(getApplicationContext(), "Unknown path",
                            Toast.LENGTH_LONG).show();
                    Log.e("Bitmap", "Unknown path");
                

                if (filePath != null) 

                    decodeFile(filePath);
                 else 
                    bitmap = null;
                
             catch (Exception e) 
                Toast.makeText(getApplicationContext(), "Internal error",
                        Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
            
        
        break;
    default:
    

图像已在文件路径中接收,现在您可以使用它了,在此代码中,我使用此设置 ImageView

  public void decodeFile(String filePath) 

    // Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, o);

    // The new size we want to scale to
    final int REQUIRED_SIZE = 1024;

    // Find the correct scale value. It should be the power of 2.
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) 
        if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;  
    

    // Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    bitmap = BitmapFactory.decodeFile(filePath, o2);

    image.setImageBitmap(bitmap);

 

【讨论】:

【参考方案3】:

首先添加这个:

ImageView profile;
Bitmap bmp;
SharedPreferences sp;
public static final int PERMISSION_REQUEST_CAMERA = 1;
private static final int PICK_FROM_GALLERY = 1;

然后在 onCreate 方法中添加这几行代码:

sp=getSharedPreferences("profilePicture",MODE_PRIVATE);
    profile=(ImageView)findViewById(R.id.profile);
    if(!sp.getString("dp","").equals(""))
        byte[] decodedString = Base64.decode(sp.getString("dp", ""), Base64.DEFAULT);
        Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
        profile.setImageBitmap(decodedByte);
    

profile.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View v) 
            openGallery();
        
    );

然后添加这些函数 openGallery() :

private void openGallery() 
    if (ActivityCompat.checkSelfPermission(ProfileActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) 
        ActivityCompat.requestPermissions(ProfileActivity.this, new String[]Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, PICK_FROM_GALLERY);
    else 
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, 1);
    

然后添加这个,onRequestPermissionsResult():

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults)

    switch (requestCode) 
        case PICK_FROM_GALLERY:
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) 
                Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(galleryIntent, PICK_FROM_GALLERY);
             else 
                Toast.makeText(ProfileActivity.this,"Not working",Toast.LENGTH_LONG).show();
                //do something like displaying a message that he didn`t allow the app to access gallery and you wont be able to let him select from gallery
            
            break;
    

onActivityResult():

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)


    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) 
        try  // When an Image is picked
            if (requestCode == PICK_FROM_GALLERY && 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]);
                String imgDecodableString = cursor.getString(columnIndex);
                cursor.close();
                // Set the Image in ImageView after decoding the String
                bmp = BitmapFactory
                        .decodeFile(imgDecodableString);
                profile.setImageBitmap(bmp);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();

                bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byte[] byteArray = stream.toByteArray();
                String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
                sp.edit().putString("dp", encodedImage).commit();
             else 
                Toast.makeText(this, "You haven't picked Image",
                        Toast.LENGTH_LONG).show();
            
         catch (Exception e) 
            e.printStackTrace();
            Toast.makeText(ProfileActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
        

    else 
        Toast.makeText(ProfileActivity.this, "You haven't picked Image",Toast.LENGTH_LONG).show();
    

不要忘记在 Manifest 文件中授予权限。

【讨论】:

以上是关于从图库中选择图像并保存以备将来使用的主要内容,如果未能解决你的问题,请参考以下文章

如何从图库中选择图像并保存到 xamarin 中的 sql 数据库

从图库/相机中选择后,图像尺寸变化[增加/减少]?

从图库中选择图像后出现空白屏幕

具有多个选项的 Android 意图,即从图库中选择图像并使用前置摄像头捕获图像

Xamarin Android - 从图库中选择图像并获取其路径

android:从图库中选择图像,然后裁剪并显示在图像视图中