[英]How to save image to gallery in Android?
我已經使用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
始終被覆蓋。
要將圖片添加到圖庫中:
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);
}
要保存多張圖片,請為每張新圖片生成一個新名稱(使用日期和時間或UUID)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.