2014-12-15 2 views
0

Я разрабатываю одно приложение, в котором я должен снимать изображение с камеры и добавлять к 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); 
} 

ответ

0

Прежде всего добавить следующее разрешение в файле манифеста вы приложения

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

Затем проверьте следующий код, который я использовал в моем приложении, чтобы установить s пользователя картинка профиля.

// на клик слушателя для запуска камеры image.setOnClickListener (новый 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); 
} 

// выборки Bitmap

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; 
} 
Смежные вопросы