在Android和iOS中讀取靜態圖像

在iOS中讀取靜態圖像

在使用swift語言編寫iOS代碼時,若想通過SWIFT直接讀取指定的圖像,可通過下列方法實現。
1. 把需要讀取的圖像添加到Xcode項目中
2. 在需要讀圖像的地方使用如下代碼讀image

        let Img1 = UIImage(named:"img1.png")
        let Img2 = UIImage(named:"img2.png")

讀取成功後就可以對Img1和Img2進行操作了。

在Android中讀取靜態圖像

在Android中讀取靜態圖像,需要首先把圖像放到 res的drawable-hdpi、drawable-mdpi、drawable-ldpi文件夾中,然後可通過如下語句讀取。

Bitmap bitmap=BitmapFactory.decodeStream(getClass().getResourceAsStream(“/res/drawable/img1.bmp”));

但這樣讀取到的圖像分辨率與原圖不一致。如果要求讀取到的圖像分辨率跟原圖保持一致則要麻煩一些。可通過如下自定義函數來實現讀取的圖像分辨率與原圖一樣。

    private Bitmap decodeResource(Resources resources, int id) {
        TypedValue value = new TypedValue();
        resources.openRawResource(id, value);
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inTargetDensity = value.density;
        return BitmapFactory.decodeResource(resources, id, opts);
    }

使用該函數讀取圖像成功後,可通過如下的方式把圖像轉化爲整形數組。

Bitmap bmp1 = decodeResource(getResources(),R.drawable.img1);
int[] dataImg = new int [bmp1.getWidth() * bmp1.getHeight()];
bmp1.getPixels(dataImg, 0, bmp1.getWidth(), 0, 0, bmp1.getWidth(), bmp1.getHeight());

注意:
原本圖像的數據是Byte流的形式,以上dataImg的存儲方式中,剛好圖像的RGBA四個Byte等於一個Int。這樣可以提高空間利用率。

Reference:
http://blog.sina.com.cn/s/blog_637607ec010158du.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章