拍照并将其放入画廊

时间:2014-01-01 06:20:52

标签: java android camera android-camera

我有一个应用程序,它显示自己的SurfaceView子类,带有摄像头预览,并有自己的捕获按钮。我使用Camera.takePicture拍摄照片,并在onPictureTaken回调中将图片数据直接输入MediaStore.Images.Media.insertImage。 (这似乎比将图像写入文件然后将其添加到图库更简单,但也许这不是一个坏主意。)

图片显示在图库中!然而,它位于画廊的尽头,这使得它很难找到。我喜欢它出现在画廊的开头,就像使用常规相机应用拍摄的照片一样。

据我所知,问题在于相机应用程序将文件命名为IMG_YYYYMMDD_[time].jpg,而我的照片最终为[unix timestamp].jpg。但我不知道如何告诉MediaStore解决这个问题。

以下是代码:

public void capture() {
    mCamera.takePicture(null, null, mPicture);
}

final PictureCallback mPicture = new PictureCallback() {
    public void onPictureTaken(byte[] data, Camera camera) {
         MediaStore.Images.Media.insertImage(getContentResolver(),
                                             BitmapFactory.decodeByteArray(data, 0, data.length),
                                             null, null);
      }
    };

1 个答案:

答案 0 :(得分:0)

实际的解决方案是添加日期元数据。最终结果(仍包含方向错误)是

final PictureCallback mPicture = new PictureCallback() {

    public void onPictureTaken(byte[] data, Camera camera) {

        // Create a media file name
        String title = "IMG_"+ new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

        String DCIM = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString();
        String DIRECTORY = DCIM + "/Camera";
        String path = DIRECTORY + '/' + title + ".jpg";

        FileOutputStream out = null;
        try {
            out = new FileOutputStream(path);
            out.write(data);
        } catch (Exception e) {
            Log.e("pictureTaken", "Failed to write data", e);
        } finally {
            try {
                out.close();
            } catch (Exception e) {
                Log.e("pictureTaken", "Failed to close file after write", e);
            }
        }

        // Insert into MediaStore.
        ContentValues values = new ContentValues(5);
        values.put(ImageColumns.TITLE, title);
        values.put(ImageColumns.DISPLAY_NAME, title + ".jpg");
        values.put(ImageColumns.DATE_TAKEN, System.currentTimeMillis());
        values.put(ImageColumns.DATA, path);
        // Clockwise rotation in degrees. 0, 90, 180, or 270.
        values.put(ImageColumns.ORIENTATION, activity.getWindowManager().getDefaultDisplay()
                .getRotation() + 90);

        Uri uri = null;
        try {
            uri = activity.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
        } catch (Throwable th)  {
            // This can happen when the external volume is already mounted, but
            // MediaScanner has not notify MediaProvider to add that volume.
            // The picture is still safe and MediaScanner will find it and
            // insert it into MediaProvider. The only problem is that the user
            // cannot click the thumbnail to review the picture.
            Log.e("pictureTaken", "Failed to write MediaStore" + th);
        }
      }
    };