0

我正在尝试在 ImageView 中插入图库中的图像,但我只看空白。没有错误。

protected static final int RESULT_LOAD_IMAGE = 1;
ImageView imgfto; 
private static int CAPTURA_FOTO = 2; 
private static int SELECT_FOTO = 1; 
private String fnombre = "";

    @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_insertarlugar);

    imgfto = (ImageView) findViewById(R.id.imgFoto);
    EditText titlugar; 
    EditText desclugar;

            titlugar = (EditText) findViewById(R.id.edit_titulo_lugar);
    String tlugar = titlugar.getText().toString();

    desclugar = (EditText) findViewById(R.id.edit_descripcion_lugar);
    String dlugar = desclugar.getText().toString();

    imgfto.setOnClickListener(new OnClickListener() {

            @Override
    public void onClick(View arg0) {
            final String[] items = {"Cámara", "Galería"};

             AlertDialog.Builder builder = new    
                     AlertDialog.Builder(Insertarlugar.this);
             builder.setTitle("Foto");
             builder.setItems(items, new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int item) {

                     int cdg = 0;
                     Intent itn = null;
                             switch (item)
                     {
                        case 1:
                        {
                          itn = new Intent(Intent.ACTION_PICK, 
                                      android.provider.MediaStore.Images.Media.
                                      INTERNAL_CONTENT_URI);
                      cdg = SELECT_FOTO;
                          break;
                        }  
                                case 2:
                                     {
                                       itn = new intent(MediaStore.ACTION_IMAGE_
                                       CAPTURE);
                           cdg = CAPTURA_FOTO;
                           fnombre =  
                                       Environment.getExternalStorageDirectory() + 
                                       "/Foto.jpg";
                           Uri fichero = Uri.fromFile(new File(fnombre));
                           itn.putExtra(MediaStore.EXTRA_OUTPUT, fichero);
                           break;
                        }
                     }   
                             startActivityForResult(itn, cdg);   
                     Toast.makeText(Insertarlugar.this, "Click\n" + item,  
                             Toast.LENGTH_SHORT).show();

                 }
             });
             AlertDialog alert = builder.create();
             alert.show(); 
         }
              });
         }

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


     if(requestCode == CAPTURA_FOTO) 
     {
        Uri imgselect = data.getData();
        String imgpath = imgselect.getPath();
                File f = new File (imgpath);
                Bitmap bm = BitmapFactory.decodeFile(f.getAbsolutePath());
                ImageView imvfto = (ImageView) findViewById(R.id.imgFoto);
                imvfto.setImageBitmap(bm);
    }

    if(requestCode == SELECT_FOTO) 
    {
        imgfto.setImageBitmap(BitmapFactory.decodeFile(fnombre));
        new MediaScannerConnectionClient() {
        private MediaScannerConnection msc = null; {
                msc = new  
                             MediaScannerConnection(getApplicationContext(), this); 
                msc.connect();
            }
            public void onMediaScannerConnected() { 
                msc.scanFile(fnombre, null);
            }
            public void onScanCompleted(String path, Uri uri) { 
                msc.disconnect();
            } 
        };      
    }
}

我也尝试了另一种方法,但结果是一样的。另一种方式是:

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


     if(requestCode == CAPTURA_FOTO) 
     {
        Uri imgselect = data.getData();
                    InputStream is;
        try 
        {
            is = getContentResolver().openInputStream(imgselect);
            BufferedInputStream bis = new BufferedInputStream(is);
            Bitmap bmap = BitmapFactory.decodeStream(bis);
            ImageView imvfto = (ImageView)findViewById(R.id.imgFoto);
            imvfto.setImageBitmap(bmap);
        }
        catch (FileNotFoundException e)
        {
            Toast.makeText(Insertarlugar.this, "Error al cargar la 
                            imagen", Toast.LENGTH_SHORT).show();
        }
                }

如何观看从图库中选择的图像?

谢谢。

4

2 回答 2

0

也许您应该检查选择图像活动的结果是否可以接受,也就是 RESULT_OK:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    //super.onActivityResult(requestCode, resultCode, data);
    if ( resultCode == RESULT_OK && requestCode == SELECT_FOTO ) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(
                selectedImage, filePathColumn, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();

            Bitmap bitmap = getImageFromPath(filePath, 512, 512);
        }
    }
}

以下是我用来解码位图的方法,您发送位图所需的尺寸,这样就不会浪费不必要的内存:

private int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int 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;
    }

    return inSampleSize;
}

private Bitmap getImageFromPath(String filePath,int reqWidth, int reqHeight) {
    BitmapFactory.Options options = new  BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, options);
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(filePath, options);
}
于 2013-08-25T21:15:15.430 回答
0

您可以使用其 URI 和setImageURI直接设置图像:

Uri imgselect = data.getData();
try 
{
    imvfto.setImageURI(imgselect );
}

然后,要调整图像,您应该使用setScaleType尝试不同的ScaleType值。这里有一些例子: http ://etcodehome.blogspot.fr/2011/05/android-imageview-scaletype-samples.html

另请查看 ImageView 的 xml 属性 ' android:adjustViewBounds ="true"' 以保持原始纵横比。

于 2013-08-27T13:44:58.620 回答