【问题标题】:How to save image to gallery in Android?如何在 Android 中将图像保存到图库?
【发布时间】:2017-01-02 22:09:01
【问题描述】:

我使用 Android Studio 创建了一个相机,并希望将拍摄的图像保存到图库中。
我用Camera2 Api,不知道怎么保存图片。
此外,我不知道我的照片存储在哪里。该应用程序说:Saved: /storage/emulated/1.jpg

这里有一些代码:

mFile = new File(Environment.getExternalStorageDirectory() + "1.jpg");

private final ImageReader.OnImageAvailableListener mOnImageAvailableListener
        = new ImageReader.OnImageAvailableListener() {

    @Override
    public void onImageAvailable(ImageReader reader) {
        mBackgroundHandler.post(new ImageSaver(reader.acquireNextImage(), mFile));
    }

};

private static class ImageSaver implements Runnable {

    /**
     * The JPEG image
     */
    private final Image mImage;
    /**
     * The file we save the image into.
     */
    private final File mFile;

    public ImageSaver(Image image, File file) {
        mImage = image;
        mFile = file;
    }

    @Override
    public void run() {
        ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        FileOutputStream output = null;
        try {
            output = new FileOutputStream(mFile);
            output.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            mImage.close();
            if (null != output) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

下一个问题是,我不知道如何存储更多照片。在这种情况下,1.jpg 总是被覆盖。

【问题讨论】:

    标签: android camera android-camera2


    【解决方案1】:

    在图库中添加您的图片:

    private void galleryAddPic() {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(mCurrentPhotoPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }
    

    See here

    要保存多张图片,为每张新图片生成一个新名称(使用日期和时间或 UUID)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-28
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多