2015-08-17 2 views
1

Мне нужно было решить проблему. Я уже искал и тестировал множество решений из этого сообщества, но кто-то мог мне помочь.Как получить изображение полного размера и уменьшенное изображение с камеры в том же намерении

У меня есть два действия, первый из них делает снимок и отправляет его другому, у которого есть ImageView, чтобы получить это (пока здесь не возникают проблемы) и запрос на вставку пути к файлу в базе данных (код которые делают эту последнюю часть хорошо).

Я думаю, что лучше для просмотра загружать изображение с низким разрешением в виде миниатюры. Поэтому, чтобы сохранить в базе данных, я хочу получить весь путь из полноразмерной картинки.

Возможно ли, что изображения должны находиться внутри определенного каталога, который я могу выбрать для имени заданных параметров функции.

Возможно, кто-нибудь знает, как установить наименьшее разрешение с камеры автоматически.

ответ

1

Если вы хотите иметь полноразмерное изображение, вам необходимо предоставить URI в дополнительных данных Intent. Выполняя это таким образом, эскиз не возвращается, поэтому вам нужно создать свой собственный.

Для изменения второго действия вы можете обновить свой ImageView с помощью пути, сохраненного в вашей БД, с помощью метода onResume() второго действия; просто убедитесь, что это не null.

public static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100; 

private boolean hasCamera(){ 
    return getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA); 
} 

public void takePicture(){ 

    // Check if there is a camera. 
    if(!hasCamera()) 
    { 
     Toast.makeText(getActivity(), "This device does not have a camera.", Toast.LENGTH_SHORT).show(); 
     return; 
    } 

    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 

    //TODO: Set this to the path you want to save, 
    //you can use Environment.getExternalStorageDirectory() 
    //and a TimeStamp to generate an unique name 
    //Save the path to your DB 
    Uri exampleUri = Uri.parse("file:///sdcard/photo.jpg"); 
    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, exampleUri); 
    startActivityForResult(takePictureIntent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE); 
} 



@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) 
    { 
     if (resultCode == RESULT_OK) 
     { 
      // Image captured and saved to fileUri specified in the Intent 
      Toast.makeText(this, "Image saved", Toast.LENGTH_LONG).show(); 

      //If you no use onResume(); to update the ImageView 
      //Another way is calling here your method for update the ImageView 
      //with the path of your DB 
     } 
     else 
     { 
      if (resultCode == RESULT_CANCELED) 
      { 
       // User cancelled the image capture 
       // So need to Delete the path from DB 
      } 
     } 
    } 

Простой способ создания эскизов:

Bitmap thumbImage = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(imagePath), THUMBSIZE, THUMBSIZE); 
imageView.setImageBitmap(thumbImage); 
1

Пример получить полную картину размера и миниатюру с camera Намерение

первым объявить кнопку, чтобы сделать снимок ...

Button takePhoto = (Button) findViewById(R.id.btn_takePhoto); 
     takePhoto.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View arg0) { 
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
        startActivityForResult(cameraIntent, 1); 
      } 
     }); 

Затем в onActivityResult мы получаем данные ...

@Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 

     if(requestCode == 1 && resultCode == Activity.RESULT_OK){ 

       //path from full size image 
       Cursor cursor = MyActivity.this.getContentResolver().query(
         MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
         new String[]{ 
           MediaStore.Images.Media.DATA, 
           MediaStore.Images.Media.DATE_ADDED, 
           MediaStore.Images.ImageColumns.ORIENTATION 
         }, 
         MediaStore.Images.Media.DATE_ADDED, 
         null, 
         "date_added DESC"); 

       Bitmap fullsize; 
       if (cursor != null && cursor.moveToFirst()) { 
        Uri uri = Uri.parse(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))); 
        String photoPath = uri.toString(); 
        cursor.close(); 
        if (photoPath != null) { 
         System.out.println("path: "+photoPath); //path from image full size 
         fullsize = decodeSampledBitmap(photoPath);//here is the bitmap of image full size 
        } 
       } 

       // do whatever you want with the Bitmap .... fullsize 


       // thumbnail 
       Bitmap thumbnail; 
       thumbnail = (Bitmap) data.getExtras().get("data"); 
       // do whatever you want with the Bitmap .... thumbnail 
      } 
     } 

Для использования утечек памяти это функции

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

      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; 
    } 



private Bitmap decodeSampledBitmap(String pathName, 
            int reqWidth, int reqHeight) { 

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

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

    // Decode bitmap with inSampleSize set 
    options.inJustDecodeBounds = false; 
    return BitmapFactory.decodeFile(pathName, options); 
} 

//I added this to have a good approximation of the screen size: 
private Bitmap decodeSampledBitmap(String pathName) { 
    Display display = getWindowManager().getDefaultDisplay(); 
    Point size = new Point(); 
    display.getSize(size); 
    int width = size.x; 
    int height = size.y; 
    return decodeSampledBitmap(pathName, width, height); 
} 

Примечание: decodeSampledBitmap функция предназначена для повышения производительности в утечки памяти, например, когда вы получаете OOM (из памяти) ....

Loading Large Bitmaps Efficiently

+0

Спасибо! Для этого решения требуется доступ к хранилищу файлов (API 23 или выше). Исключением является: «Вызывается: java.lang.SecurityException: Permission Denial: чтение com.android.providers.media.MediaProvider uri content: // media/external/images/media from pid = 6503, uid = 10060 требует android. разрешение.READ_EXTERNAL_STORAGE или grantUriPermission() ". – CoolMind