Android擷取asset下的資源圖片

來源:互聯網
上載者:User


<喎?http://www.bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+TWFpbkFjdGl2aXR5yOfPwjo8L3A+CjxwPjxwcmUgY2xhc3M9"brush:java;">package cc.testasset;import java.io.InputStream;import android.os.Bundle;import android.app.Activity;import android.content.res.AssetManager;import android.graphics.Bitmap;import android.graphics.BitmapFactory;/** * Demo描述: * 擷取asset下的資源圖片 * * 注意事項: * 1 不可以獲得asset下某個檔案夾中某資源的絕對路徑. * 因為asset是要打包到apk中的 * 2 有人說: * String filePath = "file:///android_asset/檔案名稱"; * 可以表示一個檔案的路徑.經過測試,該方法不靠譜. * 可參見代碼. */public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);init();}private void init(){//測試一:擷取asset片資源try {AssetManager assetManager = getAssets();InputStream is = assetManager.open("Fresh_01.jpg");//以下注釋掉的代碼不靠譜.若採用,會有異常//InputStream is = assetManager.open("file:///android_asset/Fresh_01.jpg");Bitmap bitmap = BitmapFactory.decodeStream(is);if (bitmap != null) {System.out.println("測試一:width=" + bitmap.getWidth() + " ,height="+ bitmap.getHeight());} else {System.out.println("bitmap == null");}} catch (Exception e) {System.out.println("異常資訊:" + e.toString());}System.out.println("======================");//測試二:擷取asset下某個檔案夾中的圖片資源try {AssetManager assetManager = getAssets();InputStream is = assetManager.open("ml_lszn_Fresh/Fresh_02.jpg");Bitmap bitmap = BitmapFactory.decodeStream(is);if (bitmap != null) {System.out.println("測試二:width=" + bitmap.getWidth() + " ,height="+ bitmap.getHeight());} else {System.out.println("bitmap == null");}} catch (Exception e) {System.out.println("異常資訊:" + e.toString());}System.out.println("======================");// 測試三:遍曆asset下某個檔案夾中的所有圖片資源try {InputStream is=null;Bitmap bitmap=null;String dirPath="ml_lszn_Fresh";String photoName=null;AssetManager assetManager = getAssets();//使用list()方法擷取某檔案夾下所有檔案的名字String [] photos=assetManager.list(dirPath);for (int i = 0; i < photos.length; i++) {photoName=photos[i];//利用dirPath+"/"+photoName組拼某檔案完整路徑is = assetManager.open(dirPath+"/"+photoName);bitmap = BitmapFactory.decodeStream(is);System.out.println("測試三: i="+i+" ,width=" + bitmap.getWidth() + " ,height="+ bitmap.getHeight());}} catch (Exception e) {System.out.println("異常資訊:" + e.toString());}}}
main.xml如下:

    



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.