Get/pick an image from Android's built-in Gallery app programmatically

前端 未结 19 1139
终归单人心
终归单人心 2020-11-22 00:49

I am trying to open an image / picture in the Gallery built-in app from inside my application.

I have a URI of the picture (the picture is located on the SD card).

相关标签:
19条回答
  • 2020-11-22 01:16

    Just in case it helps; I do this to get the Bitmap:

    InputStream is = context.getContentResolver().openInputStream(imageUri);
    Bitmap bitmap = BitmapFactory.decodeStream(is);
    
    0 讨论(0)
  • 2020-11-22 01:18

    Quickest way to open image from gallery or camera.

    Original reference : get image from gallery in android programmatically

    Following method will receive image from gallery or camera and will show it in an ImageView. Selected image will be stored internally.

    code for xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="com.exampledemo.parsaniahardik.uploadgalleryimage.MainActivity">
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="20dp"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Capture Image and upload to server" />
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Below image is fetched from server"
            android:layout_marginTop="5dp"
            android:textSize="23sp"
            android:gravity="center"
            android:textColor="#000"/>
    
        <ImageView
            android:layout_width="300dp"
            android:layout_height="300dp"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:scaleType="fitXY"
            android:src="@mipmap/ic_launcher"
            android:id="@+id/iv"/>
    
    </LinearLayout>
    

    JAVA class

    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.media.MediaScannerConnection;
    import android.os.Environment;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.Toast;
    import com.androidquery.AQuery;
    import org.json.JSONException;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Calendar;
    import java.util.HashMap;
    
    public class MainActivity extends AppCompatActivity implements AsyncTaskCompleteListener{
    
        private ParseContent parseContent;
        private Button btn;
        private ImageView imageview;
        private static final String IMAGE_DIRECTORY = "/demonuts_upload_camera";
        private final int CAMERA = 1;
        private AQuery aQuery;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            parseContent = new ParseContent(this);
            aQuery = new AQuery(this);
    
            btn = (Button) findViewById(R.id.btn);
            imageview = (ImageView) findViewById(R.id.iv);
    
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intent, CAMERA);
                }
            });
    
        }
    
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
    
            super.onActivityResult(requestCode, resultCode, data);
            if (resultCode == this.RESULT_CANCELED) {
                return;
            }
            if (requestCode == CAMERA) {
                Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
                String path = saveImage(thumbnail);
                try {
                    uploadImageToServer(path);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    
        private void uploadImageToServer(final String path) throws IOException, JSONException {
    
            if (!AndyUtils.isNetworkAvailable(MainActivity.this)) {
                Toast.makeText(MainActivity.this, "Internet is required!", Toast.LENGTH_SHORT).show();
                return;
            }
    
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("url", "https://demonuts.com/Demonuts/JsonTest/Tennis/uploadfile.php");
            map.put("filename", path);
            new MultiPartRequester(this, map, CAMERA, this);
            AndyUtils.showSimpleProgressDialog(this);
        }
    
        @Override
        public void onTaskCompleted(String response, int serviceCode) {
            AndyUtils.removeSimpleProgressDialog();
            Log.d("res", response.toString());
            switch (serviceCode) {
    
                case CAMERA:
                    if (parseContent.isSuccess(response)) {
                        String url = parseContent.getURL(response);
                        aQuery.id(imageview).image(url);
                    }
            }
        }
    
        public String saveImage(Bitmap myBitmap) {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
            File wallpaperDirectory = new File(
                    Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
            // have the object build the directory structure, if needed.
            if (!wallpaperDirectory.exists()) {
                wallpaperDirectory.mkdirs();
            }
    
            try {
                File f = new File(wallpaperDirectory, Calendar.getInstance()
                        .getTimeInMillis() + ".jpg");
                f.createNewFile();
                FileOutputStream fo = new FileOutputStream(f);
                fo.write(bytes.toByteArray());
                MediaScannerConnection.scanFile(this,
                        new String[]{f.getPath()},
                        new String[]{"image/jpeg"}, null);
                fo.close();
                Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
    
                return f.getAbsolutePath();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return "";
        }
    }
    
    0 讨论(0)
  • 2020-11-22 01:21

    Above Answers are correct. I faced an different issue where in HTC M8 my application crashes when selecting an image from gallery. I'm getting null value for image path. I fixed and optimized with the following solution. in onActivityResult method

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == RESULT_LOAD_IMAGE) && (resultCode == RESULT_OK)) {
         if (data != null) {
    
                Uri selectedImageUri = null;
                selectedImageUri = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };
    
                Cursor imageCursor = mainActivity.getContentResolver().query(
                        selectedImageUri, filePathColumn, null, null, null);
    
                if (imageCursor == null) {
                    return;
                }
    
                imageCursor.moveToFirst();
                int columnIndex = imageCursor.getColumnIndex(filePathColumn[0]);
                picturePath = imageCursor.getString(columnIndex);
                if (picturePath == null) {
                    picturePath = selectedImageUri.getPath();
                    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 = mainActivity.getContentResolver().query(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            column, sel, new String[] { id }, null);
    
                    columnIndex = cursor.getColumnIndex(column[0]);
    
                    if (cursor.moveToFirst()) {
                        picturePath = cursor.getString(columnIndex);
                    }
    
                    cursor.close();
                }
                picturePathAbs = new File(picturePath).getAbsolutePath();
                imageCursor.close();
            }
    

    }

    0 讨论(0)
  • 2020-11-22 01:22

    To display images and videos try this:

        Intent intent = new Intent();
        intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, 1);
        startActivityForResult(Intent.createChooser(intent,"Wybierz plik"), SELECT_FILE);
    
    0 讨论(0)
  • 2020-11-22 01:22
    package com.ImageConvertingDemo;
    
    import java.io.BufferedInputStream;
    import java.io.FileInputStream;
    
    import android.app.Activity;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.EditText;
    import android.widget.ImageView;
    
    public class MyActivity extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            EditText tv = (EditText)findViewById(R.id.EditText01);
            ImageView iv = (ImageView)findViewById(R.id.ImageView01);
            FileInputStream in;
            BufferedInputStream buf;
                try 
                {
                    in = new FileInputStream("/sdcard/smooth.png");
                    buf = new BufferedInputStream(in,1070);
                    System.out.println("1.................."+buf);
                    byte[] bMapArray= new byte[buf.available()];
                    tv.setText(bMapArray.toString());
                    buf.read(bMapArray);
                    Bitmap bMap = BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
    
                    /*for (int i = 0; i < bMapArray.length; i++) 
                    {
                    System.out.print("bytearray"+bMapArray[i]);
                    }*/
                    iv.setImageBitmap(bMap);
                    //tv.setText(bMapArray.toString());
                    //tv.setText(buf.toString());
                    if (in != null) 
                    {
                        in.close();
                    }
                    if (buf != null) 
                    {
                        buf.close();
                    }
    
                } 
                catch (Exception e) 
                {
                    Log.e("Error reading file", e.toString());
                }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 01:24

    here is my example, might not be as your case exactly.


    assuming that you get base64 format from your API provider, give it a file name and file extension, save it to certain location in the file system.

    public static void shownInBuiltInGallery(final Context ctx, String strBase64Image, final String strFileName, final String strFileExtension){
    
    new AsyncTask<String, String, File>() {
        @Override
        protected File doInBackground(String... strBase64Image) {
    
            Bitmap bmpImage = convertBase64StringToBitmap(strBase64Image[0], Base64.NO_WRAP);
    
            if(bmpImage == null) {
                cancel(true);
                return null;
            }
    
            byte[] byImage = null;
    
            if(strFileExtension.compareToIgnoreCase(FILE_EXTENSION_JPG) == 0) {
                byImage = convertToJpgByte(bmpImage); // convert bitmap to binary for latter use
            } else if(strFileExtension.compareToIgnoreCase(FILE_EXTENSION_PNG) == 0){
                byImage = convertToPngByte(bmpImage); // convert bitmap to binary for latter use
            } else if(strFileExtension.compareToIgnoreCase(FILE_EXTENSION_BMP) == 0){
                byImage = convertToBmpByte(bmpImage); // convert bitmap to binary for latter use
            } else {
                cancel(true);
                return null;
            }
    
            if(byImage == null) {
                cancel(true);
                return null;
            }
    
            File imageFolder = ctx.getExternalCacheDir();
    
            if(imageFolder.exists() == false){
                if(imageFolder.mkdirs() == false){
                    cancel(true);
                    return null;
                }
            }
    
            File imageFile = null;
    
            try {
                imageFile = File.createTempFile(strFileName, strFileExtension, imageFolder);
            } catch (IOException e){
                e.printStackTrace();
            }
    
            if(imageFile == null){
                cancel(true);
                return null;
            }
    
            if (imageFile.exists() == true) {
                if(imageFile.delete() == false){
                    cancel(true);
                    return null;
                }
            }
    
            FileOutputStream fos = null;
    
            try {
                fos = new FileOutputStream(imageFile.getPath());
                fos.write(byImage);
                fos.flush();
                fos.close();
            } catch (java.io.IOException e) {
                e.printStackTrace();
            } finally {
                fos = null;
            }
    
            return imageFile;
        }
    
        @Override
        protected void onPostExecute(File file) {
            super.onPostExecute(file);
    
                String strAuthority = ctx.getPackageName() + ".provider";
                Uri uriImage = FileProvider.getUriForFile(ctx, strAuthority, file);
    
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(uriImage, "image/*");
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                ctx.startActivity(intent);
    
        }
    }.execute(strBase64Image);}
    

    Don't forget to set up a proper file provider at first place in AndroidManifest.xml

            <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
    
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"/>
        </provider>
    

    where the file path is a xml in .../res/xml/file_path.xml

    <?xml version="1.0" encoding="utf-8"?>
    

    <external-files-path name="external_files" path="Accessory"/>
    
    <external-path name="ex_Download" path="Download/" />
    <external-path name="ex_Pictures" path="Pictures/" />
    
    <external-files-path name="my_Download" path="Download/" />
    <external-files-path name="my_Pictures" path="Pictures/" />
    <external-cache-path name="my_cache" path="." />
    
    <files-path name="private_Download" path="Download/" />
    <files-path name="private_Pictures" path="Pictures/" />
    <cache-path name="private_cache" path="." />
    


    Long story short, have file provider ready at first, pass Uri to Intent for known and accessible picture source, otherwise, save the picture in desired location and then pass the location (as Uri) to Intent.

    0 讨论(0)
提交回复
热议问题