簡體   English   中英

無法從相機捕獲將圖像添加到圖像視圖

[英]unable to add image to imageview from camera capture

我正在開發一個應用程序,我必須在其中從相機捕獲圖像並添加到ImageView 在這里,我在ImageView上顯示圖像時遇到問題。 如果我點擊保存按鈕,圖像第一次沒有顯示在ImageView ,但第二次顯示,請解決我的問題,我無法找到解決方案。

代碼片段:

        fromCamera.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
            /*  Log.e("OPEN", "CAMERA");

                 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                 File f = new File(android.os.Environment
                          .getExternalStorageDirectory(), "temp.jpg");
                 intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                 startActivityForResult(intent, RESUL_CameraT_LOAD_IMAGE);*/
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                File file = new File(Environment.getExternalStorageDirectory()+File.separator +    
             "fav.jpg");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(intent, RESUL_CameraT_LOAD_IMAGE);
                uploadalertDialog.dismiss();
            }
        });


    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Uri selectedImage = null;
    Bitmap bitmap;
    try {
        switch (requestCode) {
        case RESUL_CameraT_LOAD_IMAGE:
            if (resultCode == Activity.RESULT_OK) {
                // imageView.setImageResource(android.R.color.transparent);
                Log.e("GET IMAGE", "PATH");
                try{
                   File file = new File(Environment.getExternalStorageDirectory()+File.separator 
               + "fav.jpg");
                    bitmap = decodeSampledBitmapFromFile(file.getAbsolutePath(), 300, 300);
                    uloadImgView.setImageBitmap(bitmap);
                    ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 90,
                            byteArray);

                    byte[] byte_arr = byteArray.toByteArray();
                    base64 = Base64.encodeToString(byte_arr, Base64.DEFAULT);
                } 
                catch(Exception e){
                    e.printStackTrace();
                }
         }





public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) 
{ // BEST QUALITY MATCH

    //First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);

    // Calculate inSampleSize, Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    options.inPreferredConfig = Bitmap.Config.RGB_565;
    int inSampleSize = 1;

    if (height > reqHeight) 
    {
        inSampleSize = Math.round((float)height / (float)reqHeight);
    }
    int expectedWidth = width / inSampleSize;

    if (expectedWidth > reqWidth) 
    {
        //if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
        inSampleSize = Math.round((float)width / (float)reqWidth);
    }

    options.inSampleSize = inSampleSize;

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    return BitmapFactory.decodeFile(path, options);
}

首先在您的應用程序清單文件中添加以下權限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

然后檢查我在我的應用程序中使用的以下代碼來設置用戶的個人資料圖片。

// 相機的點擊監聽器觸發 image.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent cameraintent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraintent, 101);

        }
    });

//onActivityResult

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Uri selectedImage = null;
    Bitmap bitmap;

    try {
        switch (requestCode) {
        case 101:
            if (resultCode == Activity.RESULT_OK) {
                if (null != data) {
                    selectedImage = data.getData(); // the uri of the image
                                                    // taken
                    bitmap = decodeSampledBitmapFromUri(this,
                            selectedImage, 100, 100);
                    image.setImageBitmap(bitmap);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    super.onActivityResult(requestCode, resultCode, data);
}

//位圖采樣

public static Bitmap decodeSampledBitmapFromUri(Activity callingActivity,
        Uri uri, int reqWidth, int reqHeight) {
    try {
        InputStream input = callingActivity.getContentResolver()
                .openInputStream(uri);
        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inSampleSize = 2; // make the bitmap size half of the
                                    // original one
        BitmapFactory.decodeStream(input, null, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);
        input.close();

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        input = callingActivity.getContentResolver().openInputStream(uri);
        Bitmap bitmap = BitmapFactory.decodeStream(input, null, options);
        return bitmap;
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } catch (IOException e) {// TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }

}

//計算樣本大小

public static 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) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and
        // keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

暫無
暫無

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

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