简体   繁体   English

如何在Android中将图像保存到图库?

[英]How to save image to gallery in Android?

I've created a camera with Android Studio and want to save the taken image to the gallery. 我已经使用Android Studio创建了一个摄像头,并希望将拍摄的图像保存到图库中。
I use the Camera2 Api and don't really know how to save the picture. 我使用的是Camera2 Api ,但我真的不知道如何保存图片。
Moreover, I don't know, where my photo gets stored. 而且,我不知道照片存储在哪里。 The App says: Saved: /storage/emulated/1.jpg . 该应用程序说: Saved: /storage/emulated/1.jpg

Here is some code: 这是一些代码:

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

}

The next problem is, that I don't know how to store more photos. 下一个问题是,我不知道如何存储更多照片。 In this case, 1.jpg is always overwritten. 在这种情况下, 1.jpg始终被覆盖。

To add your picture in the gallery : 要将图片添加到图库中:

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 看这里

To save multiple pictures generate a new name for every new picture (use the date and time or an UUID) 要保存多张图片,请为每张新图片生成一个新名称(使用日期和时间或UUID)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM