Android 獲取drawable目錄圖片 并存入指定文件的步驟詳解
第一步:獲取存儲的路徑 我們用/sdcard/Android/data/包名/的路徑 方便我們測試查看
String path=MyApplication.getContextObject().getExternalFilesDir('').toString(); File file=new File(path);
第二步:根據(jù)該文件中存儲的路徑信息在文件系統(tǒng)上創(chuàng)建一個新的空文件
File finalImageFile = new File(file, System.currentTimeMillis() + '.jpg'); try { finalImageFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); }
第三步:將字節(jié)放入文件輸出流
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(), '圖片不存在',Toast.LENGTH_LONG).show(); return; } bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); try { fos.flush(); fos.close(); Toast.makeText(MyApplication.getContextObject(), '圖片保存在:'+ finalImageFile.getAbsolutePath(), Toast.LENGTH_LONG).show(); } catch (IOException e) { e.printStackTrace(); }
完整代碼
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(), '圖片不存在',Toast.LENGTH_LONG).show(); return; } bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); try { fos.flush(); fos.close(); Toast.makeText(MyApplication.getContextObject(), '圖片保存在:'+ finalImageFile.getAbsolutePath(), Toast.LENGTH_LONG).show(); } catch (IOException e) { e.printStackTrace(); }
總結
到此這篇關于Android 獲取drawable目錄圖片 并存入指定文件的文章就介紹到這了,更多相關android 目錄圖片存入指定文件內容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網(wǎng)!
相關文章:
1. 基于android studio的layout的xml文件的創(chuàng)建方式2. 詳解Android studio 動態(tài)fragment的用法3. 圖文詳解vue中proto文件的函數(shù)調用4. 解決Android studio xml界面無法預覽問題5. Spring Boot和Thymeleaf整合結合JPA實現(xiàn)分頁效果(實例代碼)6. 什么是python的自省7. Android如何加載Base64編碼格式圖片8. 使用Android studio查看Kotlin的字節(jié)碼教程9. Vuex localStorage的具體使用10. Vue封裝一個TodoList的案例與瀏覽器本地緩存的應用實現(xiàn)

網(wǎng)公網(wǎng)安備