2012-09-23 51 views
16

Trên một sự kiện nhấn nhất định, tôi yêu cầu người dùng thêm hình ảnh. Vì vậy, tôi cung cấp hai tùy chọn:Cách lấy đối tượng Uri từ Bitmap

  1. Để thêm từ thư viện.
  2. Để nhấp vào hình ảnh mới từ máy ảnh.

Mục đích của tôi là giữ danh sách "uri" có liên quan đến những hình ảnh đó.

Nếu người dùng chọn thư viện, sau đó tôi nhận được hình ảnh uri (khá đơn giản). Nhưng nếu anh ta chọn máy ảnh, sau khi chụp ảnh, tôi sẽ nhận được đối tượng Bitmap của bức ảnh đó.

Bây giờ làm cách nào để chuyển đổi đối tượng Bitmap đó thành uri, hoặc nói cách khác, làm cách nào tôi có thể nhận đối tượng Uri tương đối của đối tượng bitmap đó?

Cảm ơn.

+0

Điều này có thể giúp http: // stackoverflow.com/questions/7636697/get-path-và-filename-from-camera-intent-result –

+0

một số mã được mã hóa khá nhiều. Tôi không muốn mã hóa cứng tên tệp của hình ảnh. Và không nhất thiết là hình ảnh được lưu trong thư mục DCIM .. –

Trả lời

0

Tôi đã thử đoạn mã sau đây từ post I mentioned in my comment.. và nó hoạt động tốt cho tôi.

/** 
* Gets the last image id from the media store 
* 
* @return 
*/ 
private int getLastImageId() { 
    final String[] imageColumns = { MediaStore.Images.Media._ID, 
      MediaStore.Images.Media.DATA }; 
    final String imageOrderBy = MediaStore.Images.Media._ID + " DESC"; 
    Cursor imageCursor = managedQuery(
      MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns, 
      null, null, imageOrderBy); 
    if (imageCursor.moveToFirst()) { 
     int id = imageCursor.getInt(imageCursor 
       .getColumnIndex(MediaStore.Images.Media._ID)); 
     String fullPath = imageCursor.getString(imageCursor 
       .getColumnIndex(MediaStore.Images.Media.DATA)); 
     Log.d(getClass().getSimpleName(), "getLastImageId::id " + id); 
     Log.d(getClass().getSimpleName(), "getLastImageId::path " 
       + fullPath); 
     imageCursor.close(); 
     return id; 
    } else { 
     return 0; 
    } 
} 

đầu ra trong logcat:

09-24 16:36:24.500: getLastImageId::id 70 
09-24 16:36:24.500: getLastImageId::path /mnt/sdcard/DCIM/Camera/2012-09-24 16.36.20.jpg 

Ngoài ra tôi không thấy bất kỳ tên harcoded trong đoạn mã trên. Hy vọng điều này sẽ hữu ích.

0
Try To Use this May Be Helpful to you : 

new AsyncTask<Void, Integer, Void>() { 
      protected void onPreExecute() { 
      }; 

      @Override 
      protected Void doInBackground(Void... arg0) { 
       imageAdapter.images.clear(); 
       initializeVideoAndImage(); 
       return null; 
      } 

      protected void onProgressUpdate(Integer... integers) { 
       imageAdapter.notifyDataSetChanged(); 
      } 

      public void initializeVideoAndImage() { 
       final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Thumbnails._ID }; 
       String orderBy = MediaStore.Images.Media._ID; 
       Cursor imageCursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy); 

       final String[] videocolumns = { MediaStore.Video.Thumbnails._ID, MediaStore.Video.Media.DATA }; 
       orderBy = MediaStore.Video.Media._ID; 
       Cursor videoCursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videocolumns, null, null, orderBy); 
       int i = 0; 
       int image_column_index = 0; 

       if (imageCursor != null) { 
        image_column_index = imageCursor.getColumnIndex(MediaStore.Images.Media._ID); 
        int count = imageCursor.getCount(); 
        for (i = 0; i < count; i++) { 
         imageCursor.moveToPosition(i); 
         int id = imageCursor.getInt(image_column_index); 
         ImageItem imageItem = new ImageItem(); 
         imageItem.id = id; 
         imageAdapter.images.add(imageItem); 

        } 
       } 

       if (videoCursor != null) { 
        image_column_index = videoCursor.getColumnIndex(MediaStore.Video.Media._ID); 
        int count = videoCursor.getCount(); 
        for (i = 0; i < count; i++) { 
         videoCursor.moveToPosition(i); 
         int id = videoCursor.getInt(image_column_index); 
         ImageItem imageItem = new ImageItem(); 
         imageItem.id = id; 
         imageAdapter.images.add(imageItem); 
        } 
       } 
       publishProgress(i); 
       if (imageCursor != null) { 
        image_column_index = imageCursor.getColumnIndex(MediaStore.Images.Media._ID); 
        int count = imageCursor.getCount(); 
        for (i = 0; i < count; i++) { 
         imageCursor.moveToPosition(i); 
         int id = imageCursor.getInt(image_column_index); 
         int dataColumnIndex = imageCursor.getColumnIndex(MediaStore.Images.Media.DATA); 
         ImageItem imageItem = imageAdapter.images.get(i); 
         Bitmap img = MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), id, MediaStore.Images.Thumbnails.MICRO_KIND, null); 
         int column_index = imageCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
         imageItem.imagePath = imageCursor.getString(column_index); 
         imageItem.videoPath = ""; 
         try { 
          File imageFile = new File(Environment.getExternalStorageDirectory(), "image" + i); 
          imageFile.createNewFile(); 
          ByteArrayOutputStream bos = new ByteArrayOutputStream(); 

          if (bos != null && img != null) { 
           img.compress(Bitmap.CompressFormat.PNG, 100, bos); 
          } 
          byte[] bitmapData = bos.toByteArray(); 
          FileOutputStream fos = new FileOutputStream(imageFile); 
          fos.write(bitmapData); 
          fos.close(); 
          imageItem.thumbNailPath = imageFile.getAbsolutePath(); 
          try { 
           boolean cancelled = isCancelled(); 
           // if async task is not cancelled, update the 
           // progress 
           if (!cancelled) { 
            publishProgress(i); 
            SystemClock.sleep(100); 

           } 

          } catch (Exception e) { 
           Log.e("Error", e.toString()); 
          } 
          // publishProgress(); 
         } catch (IOException e) { 
          e.printStackTrace(); 
         } 
         // imageAdapter.images.add(imageItem); 
        } 
       } 
       imageCursor.close(); 

       if (videoCursor != null) { 
        image_column_index = videoCursor.getColumnIndex(MediaStore.Video.Media._ID); 
        int count = videoCursor.getCount() + i; 
        for (int j = 0; i < count; i++, j++) { 
         videoCursor.moveToPosition(j); 
         int id = videoCursor.getInt(image_column_index); 
         int column_index = videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA); 
         ImageItem imageItem = imageAdapter.images.get(i); 
         imageItem.imagePath = videoCursor.getString(column_index); 
         imageItem.videoPath = imageItem.imagePath; 
         System.out.println("External : " + imageItem.videoPath); 
         try { 
          File imageFile = new File(Environment.getExternalStorageDirectory(), "imageV" + i); 
          imageFile.createNewFile(); 
          ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
          MediaMetadataRetriever mediaVideo = new MediaMetadataRetriever(); 
          mediaVideo.setDataSource(imageItem.videoPath); 
          Bitmap videoFiles = mediaVideo.getFrameAtTime(); 
          videoFiles = ThumbnailUtils.extractThumbnail(videoFiles, 96, 96); 
          if (bos != null && videoFiles != null) { 
           videoFiles.compress(Bitmap.CompressFormat.JPEG, 100, bos); 

          } 
          byte[] bitmapData = bos.toByteArray(); 
          FileOutputStream fos = new FileOutputStream(imageFile); 
          fos.write(bitmapData); 
          fos.close(); 
          imageItem.imagePath = imageFile.getAbsolutePath(); 
          imageItem.thumbNailPath = imageFile.getAbsolutePath(); 
          try { 
           boolean cancelled = isCancelled(); 
           // if async task is not cancelled, update the 
           // progress 
           if (!cancelled) { 
            publishProgress(i); 
            SystemClock.sleep(100); 

           } 

          } catch (Exception e) { 
           Log.e("Error", e.toString()); 
          } 
         } catch (IOException e) { 
          e.printStackTrace(); 
         } 

        } 
       } 
       videoCursor.close(); 
      } 

      protected void onPostExecute(Void result) { 
       imageAdapter.notifyDataSetChanged(); 
      }; 

     }.execute(); 

    } 
31

Tôi có cùng vấn đề trong dự án của mình, vì vậy tôi thực hiện theo phương pháp đơn giản (click here) để lấy Uri từ bitmap.

public Uri getImageUri(Context inContext, Bitmap inImage) { 
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes); 
    String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null); 
    return Uri.parse(path); 
} 
+4

'Images.Media.insertImage' bây giờ là' MediaStore.Images.Media.insertImage' Điều thứ hai bạn cần ghi nhớ để thêm quyền này: ' ' –

+8

Nó trả về đường dẫn null trong android 6.0 –

+0

Hai thiết bị marshmallow, Motorola' trả về đường dẫn' nhưng Samsung 'trả về null'. Bất kỳ giúp đỡ? – sud007

5
Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null); 

dòng nêu trên tạo ra một hình ảnh thu nhỏ sử dụng bitmap, có thể tiêu thụ một số không gian thêm trong thiết bị Android của bạn.

Phương pháp này có thể giúp bạn lấy Uri từ bitmap mà không tốn thêm chút bộ nhớ nào.

public Uri bitmapToUriConverter(Bitmap mBitmap) { 
    Uri uri = null; 
    try { 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    // Calculate inSampleSize 
    options.inSampleSize = calculateInSampleSize(options, 100, 100); 

    // Decode bitmap with inSampleSize set 
    options.inJustDecodeBounds = false; 
    Bitmap newBitmap = Bitmap.createScaledBitmap(mBitmap, 200, 200, 
      true); 
    File file = new File(getActivity().getFilesDir(), "Image" 
      + new Random().nextInt() + ".jpeg"); 
    FileOutputStream out = getActivity().openFileOutput(file.getName(), 
      Context.MODE_WORLD_READABLE); 
    newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); 
    out.flush(); 
    out.close(); 
    //get absolute path 
    String realPath = file.getAbsolutePath(); 
    File f = new File(realPath); 
    uri = Uri.fromFile(f); 

    } catch (Exception e) { 
    Log.e("Your Error Message", e.getMessage()); 
    } 
return uri; 
} 
+0

calculInSampleSize là gì ?? Vui lòng thêm phương thức cho nó –

+0

@Anand: http://stackoverflow.com/questions/2641726/decoding-bitmaps-in-android-with-the-right-size này có thể giúp bạn, nếu bạn tìm được giải pháp thích hợp thì vui lòng thông báo. – Hanan

+0

bạn có thể bỏ qua inSampleSize. Việc đặt mẫu thành 2 sẽ giảm chất lượng hình ảnh xuống 2, như thể chỉ lấy từng pixel thứ hai của hình ảnh, giống như vậy. Đặt 1 hoặc không thiết lập tùy chọn này sẽ là ok. – lxknvlk

0

Đây là những gì hiệu quả đối với tôi. Ví dụ: thu nhỏ hình thu nhỏ từ video dưới dạng bitmap. Sau đó, chúng ta có thể chuyển đổi đối tượng bitmap thành đối tượng uri.

String videoPath = mVideoUri.getEncodedPath(); 
System.out.println(videoPath); //prints to console the path of the saved video 
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Images.Thumbnails.MINI_KIND); 

Uri thumbUri = getImageUri(this, thumb); 
0

nếu bạn lấy hình ảnh từ máy ảnh, không có cách nào lấy Uri từ bitmap, vì vậy bạn nên lưu bitmap trước.

ra mắt máy ảnh ý

startActivityForResult(Intent(MediaStore.ACTION_IMAGE_CAPTURE), 8) 

sau đó, ghi đè

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { 

    if (resultCode == Activity.RESULT_OK && requestCode == 8) { 
     val bitmap = data?.extras?.get("data") as Bitmap 

     val uri = readWriteImage(bitmap) 
    } 
} 

cũng tạo ra phương pháp để lưu trữ bitmap và sau đó trả lại Uri

fun readWriteImage(bitmap: Bitmap): Uri { 
    // store in DCIM/Camera directory 
    val dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) 
    val cameraDir = File(dir, "Camera/") 

    val file = if (cameraDir.exists()) { 
     File(cameraDir, "LK_${System.currentTimeMillis()}.png") 
    } else { 
     cameraDir.mkdir() 
     File(cameraDir, "LK_${System.currentTimeMillis()}.png") 
    } 

    val fos = FileOutputStream(file) 
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos) 
    fos.flush() 
    fos.close() 

    Uri.fromFile(file) 
} 

PS: dont quên Thêm Permission và giấy phép chạy bộ xử lý (API> = 23)

Các vấn đề liên quan