我想從drawable保存圖片。該應用程序的工作原理,但只適用於API 22以下的Android版本。在較新的版本中,圖像不會保存在圖庫中。該代碼僅適用於某些android版本
我的代碼:
public class MainActivity extends AppCompatActivity {
Bitmap anImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Drawable myDrawable = getResources().getDrawable(R.drawable.tapeta1, null);
anImage = ((BitmapDrawable) myDrawable).getBitmap();
}
public void addImageToGallery(View view) {
int e = view.getId();
switch (e) {
case R.id.button:
saveImageToExternalStorage(anImage);
Toast.makeText(getApplicationContext(), "Saved successfully, Check gallery", Toast.LENGTH_SHORT).show();
break;
}
}
private void saveImageToExternalStorage(Bitmap finalBitmap) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/saved_images_1");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
}
非常抱歉應該是「API 23以下」 –