Android Obtain drawable Directory Picture and Store in Specified File

  • 2021-11-30 01:30:18
  • OfStack

Step 1: Get the path to the store. We use the /sdcard/Android/data/ The path of the package name/is convenient for us to test and view


 String path=MyApplication.getContextObject().getExternalFilesDir("").toString();
 File file=new File(path);

Step 2: Create a new empty file on the file system based on the path information stored in the file


File finalImageFile = new File(file, System.currentTimeMillis() + ".jpg");
 try {
   finalImageFile.createNewFile();
 } catch (IOException e) {
   e.printStackTrace();
 }

Step 3: Put bytes into the file output stream


FileOutputStream fos = null;
 try {
   fos = new FileOutputStream(finalImageFile);
 } catch (FileNotFoundException e) {
   e.printStackTrace();
 }

Step 4: Compress the picture into picture format


 BitmapDrawable bitmapDrawable = (BitmapDrawable)MyApplication.getContextObject().getResources().getDrawable(R.drawable.account);
 Bitmap bitmap=bitmapDrawable.getBitmap();
 if (bitmap == null) {
   Toast.makeText(MyApplication.getContextObject(), " Picture does not exist ",Toast.LENGTH_LONG).show();
   return;
 }
 bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
 try {
   fos.flush();
   fos.close();
   Toast.makeText(MyApplication.getContextObject(), " The picture is saved in: "+ finalImageFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
 } catch (IOException e) {
   e.printStackTrace();
 }

Complete code


 String path=MyApplication.getContextObject().getExternalFilesDir("").toString();
 File file=new File(path);
 
 File finalImageFile = new File(file, System.currentTimeMillis() + ".jpg");
 try {
   finalImageFile.createNewFile();
 } catch (IOException e) {
   e.printStackTrace();
 }
 
 FileOutputStream fos = null;
 try {
   fos = new FileOutputStream(finalImageFile);
 } catch (FileNotFoundException e) {
   e.printStackTrace();
 }
 
 BitmapDrawable bitmapDrawable = (BitmapDrawable)MyApplication.getContextObject().getResources().getDrawable(R.drawable.account);
 Bitmap bitmap=bitmapDrawable.getBitmap();
 if (bitmap == null) {
   Toast.makeText(MyApplication.getContextObject(), " Picture does not exist ",Toast.LENGTH_LONG).show();
   return;
 }
 bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
 try {
   fos.flush();
   fos.close();
   Toast.makeText(MyApplication.getContextObject(), " The picture is saved in: "+ finalImageFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
 } catch (IOException e) {
   e.printStackTrace();
 }

Summarize


Related articles: