簡體   English   中英

無法從圖庫加載圖像

[英]Can't load an image from gallery

我正在嘗試從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();
        }
                }

如何觀看從圖庫中選擇的圖像?

謝謝。

也許您應該檢查選擇圖像活動的結果是否可接受,也稱為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);
}

您可以使用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”'以保持原始的寬高比。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM