如何从支持的API&GT画廊获得图像= 19安培; API所述19两者兼而有之? [英] How to get image from gallery which supports for API>=19 & API<19 both?

查看:239
本文介绍了如何从支持的API&GT画廊获得图像= 19安培; API所述19两者兼而有之?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

图像不进口,每次当我在Android图库PIC形象。

\r
\r

意向书I =新意图(Intent.ACTION_PICK,android.provider.MediaStore.Images .Media.EXTERNAL_CONTENT_URI);\r
startActivityForResult(ⅰ,LOAD_IMAGE_RESULTS);\r
    \r
\r
super.onActivityResult(要求code,结果code,数据);\r
BitmapFactory.Options BitmapFactoryOptionsbfo =新BitmapFactory.Options();\r
BitmapFactoryOptionsbfo.in preferredConfig = Bitmap.Config.RGB_565;\r
如果(要求code == LOAD_IMAGE_RESULTS&放大器;&安培;结果code == RESULT_OK\r
&功放;&安培;数据!= NULL){\r
imgUri = data.getData();\r
//让我们使用内容解析器读取摄取的图像路径\r
的String []文件路径= {} MediaStore.Images.Media.DATA;\r
光标光标= getContentResolver()查询(imgUri,文件路径,空,\r
NULL,NULL);\r
cursor.moveToFirst();\r
字符串的ImagePath = cursor.getString(光标\r
.getColumnIndex(文件路径[0]));\r
\r
BMP = BitmapFactory.de codeFILE(的ImagePath);\r
\r
cursor.close();\r
}

\r

\r
\r    图像不进口每次,BMP一些上设置ImageView的什么都没有。

如何从画廊得到的图片其中支持API> = 19安培; API所述19 两个...


解决方案

这code'll解决的 SDK&LT的问题; API11 SDK> = 11安培;&安培; SDK< 19 SDK> 19

声明它在全球范围内

 公众最终诠释GALLERY_PHOTO = 2;
位图newbitmap;
私人乌里了fileURI;

使用这种方法来启动影像选择器

 公共无效callGallery(){
    意向意图=新的Intent();
    intent.setType(图像/ *);
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(意向,选择图片),
            GALLERY_PHOTO);
}

在默认使用此条件 @Overide的onActivityResult(INT申请code,INT结果code,意图数据)

 如果(要求code == GALLERY_PHOTO){        如果(结果code == RESULT_OK){            // SDK< API11
            如果(Build.VERSION.SDK_INT&下; 11){                尝试{
                    真实路径= RealPathUtil.getRealPathFromURI_BelowAPI11(
                            Yourclassname.this,
                            data.getData());
                    setTextViews(Build.VERSION.SDK_INT,data.getData()
                            .getPath(),真实路径);
                }赶上(例外五){                    e.printStackTrace();
                    乌里selectedImage = data.getData();
                    的String [] = filePathColumn {MediaStore.Images.Media.DATA};                    光标光标= getContentResolver()
                            .query(selectedImage,filePathColumn,空,
                                    NULL,NULL);
                    cursor.moveToFirst();                    INT参数:columnIndex =光标
                            .getColumnIndex(filePathColumn [0]);
                    字符串文件路径= cursor.getString(参数:columnIndex);
                    cursor.close();                    newbitmap = BitmapFactory.de codeFILE(文件路径);
                    imageview.setImageBitmap(newbitmap);                }
            }            // SDK> = 11安培;&安培; SDK< 19
            否则如果(Build.VERSION.SDK_INT所述19){                尝试{
                    真实路径= RealPathUtil.getRealPathFromURI_API11to18(
                            yourclassname.this,
                            data.getData());
                    setTextViews(Build.VERSION.SDK_INT,data.getData()
                            .getPath(),真实路径);
                }赶上(例外E1){                    e1.printStackTrace();
                    乌里selectedImage = data.getData();
                    的String [] = filePathColumn {MediaStore.Images.Media.DATA};                    光标光标= getContentResolver()
                            .query(selectedImage,filePathColumn,空,
                                    NULL,NULL);
                    cursor.moveToFirst();                    INT参数:columnIndex =光标
                            .getColumnIndex(filePathColumn [0]);
                    字符串文件路径= cursor.getString(参数:columnIndex);
                    cursor.close();                    newbitmap = BitmapFactory.de codeFILE(文件路径);
                    imageview.setImageBitmap(newbitmap);                }
            }            其他{
                尝试{                    真实路径= RealPathUtil.getRealPathFromURI_API19(
                            yourclassname.this,
                            data.getData());                    setTextViews(Build.VERSION.SDK_INT,data.getData()
                            .getPath(),真实路径);                }赶上(例外五){                    乌里selectedImage = data.getData();
                    的String [] = filePathColumn {MediaStore.Images.Media.DATA};                    光标光标= getContentResolver()
                            .query(selectedImage,filePathColumn,空,
                                    NULL,NULL);
                    cursor.moveToFirst();                    INT参数:columnIndex =光标
                            .getColumnIndex(filePathColumn [0]);
                    字符串文件路径= cursor.getString(参数:columnIndex);
                    cursor.close();                    newbitmap = BitmapFactory.de codeFILE(文件路径);
                    imageview.setImageBitmap(newbitmap);                }
            }            // 结束        }否则如果(结果code == RESULT_CANCELED){            Toast.makeText(getApplicationContext()已取消,
                    Toast.LENGTH_SHORT).show();
        }其他{
            //未能捕捉到的图像
            Toast.makeText(getApplicationContext(),                    哎呀!失败挑图像,Toast.LENGTH_SHORT).show();
        }    }

在你的类包含这个方法

 私人无效setTextViews(INT SDK,字符串uriPath,弦乐真实路径){    乌里uriFromPath = Uri.fromFile(新文件(真实路径));    了fileURI = uriFromPath;    尝试{
        newbitmap = BitmapFactory.de codeStream(getContentResolver()
                .openInputStream(fileURI所));
    }赶上(FileNotFoundException异常五){
        e.printStackTrace();
    }
    imageview.setImageBitmap(newbitmap);    Log.d(状态,Build.VERSION.SDK_INT:+ SDK);
    Log.d(状态,URI路径:+ fileURI所);
    Log.d(状态,真正的路径:+真实路径);}

创建 RealPathUtil.class 这个辅助方法

 公共类RealPathUtil {@燮pressLint(NewApi)
公共静态字符串getRealPathFromURI_API19(上下文的背景下,开放的URI){
    串文件路径=;
    串wholeID = DocumentsContract.getDocumentId(URI);     //分割在结肠,在阵列中使用的第二项
     串ID = wholeID.split(:)[1];     的String [] =列{} MediaStore.Images.Media.DATA;     //其中id等于
     字符串SEL = MediaStore.Images.Media._ID +=;     光标光标= context.getContentResolver()查询(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                               列,SEL,新的String [] {ID},NULL);     INT参数:columnIndex = cursor.getColumnIndex(列[0]);     如果(cursor.moveToFirst()){
         文件路径= cursor.getString(参数:columnIndex);
     }     cursor.close();     返回文件路径;
}
@燮pressLint(NewApi)
公共静态字符串getRealPathFromURI_API11to18(上下文的背景下,乌里contentUri){
      的String [] = PROJ {MediaStore.Images.Media.DATA};
      字符串结果= NULL;      CursorLoader cursorLoader =新CursorLoader(
              的背景下,
        contentUri,PROJ,NULL,NULL,NULL);
      光标光标= cursorLoader.loadInBackground();      如果(指针!= NULL){
       INT与Column_Index =
         cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
       cursor.moveToFirst();
       结果= cursor.getString(Column_Index中);
      }      返回结果;
}公共静态字符串getRealPathFromURI_BelowAPI11(上下文的背景下,乌里contentUri){
           的String [] = PROJ {MediaStore.Images.Media.DATA};
           光标光标= context.getContentResolver()查询(contentUri,凸出,NULL,NULL,NULL);
           INT与Column_Index
      = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
           cursor.moveToFirst();
           返回cursor.getString(Column_Index中);
   }
}

希望这将解决您的问题。

Image is not importing, every time when I pic image from gallery in Android.

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

super.onActivityResult(requestCode, resultCode, data);
BitmapFactory.Options BitmapFactoryOptionsbfo = new BitmapFactory.Options();
BitmapFactoryOptionsbfo.inPreferredConfig = Bitmap.Config.RGB_565;
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK
				&& data != null) {
			imgUri = data.getData();
			// Let's read picked image path using content resolver
			String[] filePath = { MediaStore.Images.Media.DATA };
			Cursor cursor = getContentResolver().query(imgUri, filePath, null,
					null, null);
			cursor.moveToFirst();
			String imagePath = cursor.getString(cursor
					.getColumnIndex(filePath[0]));

			bmp = BitmapFactory.decodeFile(imagePath);

			cursor.close();
}

image is not importing every time ,some bmp sets nothing on imageview.

how to get image from gallery which supports for API>=19 & API<19 both...

解决方案

This code'll solve the problem for SDK < API11, SDK >= 11 && SDK < 19 and SDK > 19

Declare it Globally

public final int GALLERY_PHOTO = 2;
Bitmap newbitmap;
private Uri fileUri;

Use this Method to Start Image chooser

public void callGallery() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"),
            GALLERY_PHOTO);
}

Use this condition in Default @Overide onActivityResult(int requestCode, int resultCode, Intent data)

if (requestCode == GALLERY_PHOTO) {

        if (resultCode == RESULT_OK) {

            // SDK < API11
            if (Build.VERSION.SDK_INT < 11) {

                try {
                    realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(
                            Yourclassname.this,
                            data.getData());
                    setTextViews(Build.VERSION.SDK_INT, data.getData()
                            .getPath(), realPath);
                } catch (Exception e) {

                    e.printStackTrace();
                    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 filePath = cursor.getString(columnIndex);
                    cursor.close();

                    newbitmap = BitmapFactory.decodeFile(filePath);
                    imageview.setImageBitmap(newbitmap);

                }
            }

            // SDK >= 11 && SDK < 19
            else if (Build.VERSION.SDK_INT < 19) {

                try {
                    realPath = RealPathUtil.getRealPathFromURI_API11to18(
                            yourclassname.this,
                            data.getData());
                    setTextViews(Build.VERSION.SDK_INT, data.getData()
                            .getPath(), realPath);
                } catch (Exception e1) {

                    e1.printStackTrace();
                    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 filePath = cursor.getString(columnIndex);
                    cursor.close();

                    newbitmap = BitmapFactory.decodeFile(filePath);
                    imageview.setImageBitmap(newbitmap);

                }
            }

            else {
                try {

                    realPath = RealPathUtil.getRealPathFromURI_API19(
                            yourclassname.this,
                            data.getData());

                    setTextViews(Build.VERSION.SDK_INT, data.getData()
                            .getPath(), realPath);

                } catch (Exception e) {

                    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 filePath = cursor.getString(columnIndex);
                    cursor.close();

                    newbitmap = BitmapFactory.decodeFile(filePath);
                    imageview.setImageBitmap(newbitmap);

                }
            }

            // end

        } else if (resultCode == RESULT_CANCELED) {

            Toast.makeText(getApplicationContext(), "Canceled",
                    Toast.LENGTH_SHORT).show();
        } else {
            // failed to capture image
            Toast.makeText(getApplicationContext(),

                    "Oops!! Failed to pick Image", Toast.LENGTH_SHORT).show();
        }

    }

Include this method in your class

private void setTextViews(int sdk, String uriPath, String realPath) {

    Uri uriFromPath = Uri.fromFile(new File(realPath));

    fileUri = uriFromPath;

    try {
        newbitmap = BitmapFactory.decodeStream(getContentResolver()
                .openInputStream(fileUri));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }


    imageview.setImageBitmap(newbitmap);

    Log.d("Status", "Build.VERSION.SDK_INT:" + sdk);
    Log.d("Status", "URI Path:" + fileUri);
    Log.d("Status", "Real Path: " + realPath);

}

Create this Helper Methods in RealPathUtil.class

public class RealPathUtil {

@SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
    String filePath = "";
    String wholeID = DocumentsContract.getDocumentId(uri);

     // 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 = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
                               column, sel, new String[]{ id }, null);

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

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

     cursor.close();

     return filePath;
}


@SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
      String[] proj = { MediaStore.Images.Media.DATA };
      String result = null;

      CursorLoader cursorLoader = new CursorLoader(
              context, 
        contentUri, proj, null, null, null);        
      Cursor cursor = cursorLoader.loadInBackground();

      if(cursor != null){
       int column_index = 
         cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
       cursor.moveToFirst();
       result = cursor.getString(column_index);
      }

      return result;  
}

public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
           String[] proj = { MediaStore.Images.Media.DATA };
           Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
           int column_index
      = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
           cursor.moveToFirst();
           return cursor.getString(column_index);
   }
}

Hope this will solve your Problem.

这篇关于如何从支持的API&GT画廊获得图像= 19安培; API所述19两者兼而有之?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆