android獲取圖片尺寸的兩種方式及bitmap的縮放操作
我就廢話不多說(shuō)了,大家還是直接看代碼吧~
//Uri.parse('file://'+result.getImage().getCompressPath())) String path=uri.getPath(); Log.e('圖片路徑',path+''); SpannableString spannableString=new SpannableString(path); //方法一:通過(guò)uri把圖片轉(zhuǎn)化為bitmap的方法 Bitmap bitmap= BitmapFactory.decodeFile(path); int height= bitmap.getHeight(); int width= bitmap.getWidth(); Log.e('通過(guò)bitmap獲取到的圖片大小','width:'+width+'height'+height); //方法二:使用Options類來(lái)獲取 BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true;//這個(gè)參數(shù)設(shè)置為true才有效, Bitmap bmp = BitmapFactory.decodeFile(path, options);//這里的bitmap是個(gè)空 if(bmp==null){ Log.e('通過(guò)options獲取到的bitmap為空','==='); } int outHeight=options.outHeight; int outWidth= options.outWidth; Log.e('通過(guò)Options獲取到的圖片大小','width:'+outWidth+'height'+outHeight);
關(guān)于兩種方法:
第一種: 直接把bitmap加載到內(nèi)存中,通過(guò)對(duì)bitmap的測(cè)量,得出寬高,由于這個(gè)方法直接把圖片引入內(nèi)存,如果圖片過(guò)大,將會(huì)引發(fā)OOM;
第二種:bitmap.options類為bitmap的裁剪類,通過(guò)他可以實(shí)現(xiàn)bitmap的裁剪;如果不設(shè)置裁剪后的寬高和裁剪比例,返回的bitmap對(duì)象將為空,但是這個(gè)對(duì)象存儲(chǔ)了原bitmap的寬高信息。
打log輸出信息如下:
縮放:
Bitmap bitmap=null; BitmapFactory.Options options=new BitmapFactory.Options(); options.inSampleSize=2; options.inJustDecodeBounds = false; if(path.equals('a1')){ bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.a1,options);
inSampleSize表示縮放比例
補(bǔ)充知識(shí):android獲取Bitmap對(duì)象,獲取圖片寬高
android在不加載圖片的前提下獲得圖片的寬高
public static int[] getImageWidthHeight(String path){ BitmapFactory.Options options = new BitmapFactory.Options(); /** * 最關(guān)鍵在此,把options.inJustDecodeBounds = true; * 這里再decodeFile(),返回的bitmap為空,但此時(shí)調(diào)用options.outHeight時(shí),已經(jīng)包含了圖片的高了 */ options.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeFile(path, options); // 此時(shí)返回的bitmap為null /** *options.outHeight為原始圖片的高 */ return new int[]{options.outWidth,options.outHeight};}
通過(guò)BitmapFactory從不同位置獲取Bitmap
1.資源文件(drawable/mipmap/raw)
BitmapFactory.decodeResource(getResources(), R.mipmap.slim_lose_weight_plan_copenhagen,options);
2.資源文件(assets)
InputStream is = getActivity().getAssets().open('bitmap.png');
BitmapFactory.decodeStream(is);
3.內(nèi)存卡文件
bitmap = BitmapFactory.decodeFile('/sdcard/bitmap.png');
4.網(wǎng)絡(luò)文件
bitmap = BitmapFactory.decodeStream(is);
可根據(jù)BitmapFactory獲取圖片時(shí)傳入option,通過(guò)上述方法獲取圖片的寬高
以上這篇android獲取圖片尺寸的兩種方式及bitmap的縮放操作就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. js實(shí)現(xiàn)跳一跳小游戲2. JVM之class文件結(jié)構(gòu)3. js實(shí)現(xiàn)貪吃蛇小游戲(加墻)4. XMLDOM對(duì)象方法:對(duì)象屬性5. python對(duì)批量WAV音頻進(jìn)行等長(zhǎng)分割的方法實(shí)現(xiàn)6. Html5播放器實(shí)現(xiàn)倍速播放的方法示例7. asp.net core 認(rèn)證和授權(quán)實(shí)例詳解8. CSS linear-gradient屬性案例詳解9. Ajax報(bào)錯(cuò)400的參考解決辦法10. Python中Anaconda3 安裝gdal庫(kù)的方法
