55
技術社區[雲棲]
android 讀取本地或網絡圖片,轉換為Bitmap -
在做android項目時,我們經常需要從本地或者網絡讀取圖片,並轉換為Bitmap圖片,以便使用,下麵是讀取本地圖片並轉換的方法:
/**
* 得到本地或者網絡上的bitmap url - 網絡或者本地圖片的絕對路徑,比如:
*
* A.網絡路徑: url="https://blog.foreverlove.us/girl2.png" ;
*
* B.本地路徑:url="file://mnt/sdcard/photo/image.png";
*
* C.支持的圖片格式 ,png, jpg,bmp,gif等等
*
* @param url
* @return
*/
public static Bitmap GetLocalOrNetBitmap(String url)
{
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try
{
in = new BufferedInputStream(new URL(url).openStream(), Constant.IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, Constant.IO_BUFFER_SIZE);
copy(in, out);
out.flush();
byte[] data = dataStream.toByteArray();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
data = null;
return bitmap;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}說明:Constant.IO_BUFFER_SIZE 是一個常量而已,可以改成常數,比如2*1024,其實取決於你的圖片大小,自己根據圖片的大小自己設定吧。。。。
附加的copy函數
private static void copy(InputStream in, OutputStream out)
throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
最後更新:2017-04-02 17:28:38
上一篇:
Android數據庫(SqlLite)操作和db文件查看
下一篇:
mime types 大全--來自ubuntu /etc/mime.types
利用iOS API編寫簡單微博客戶端全過程
HTAP數據庫 PostgreSQL 場景與性能測試之 18 - (OLAP) 用戶畫像圈人場景 - 數組包含查詢與聚合
機器視覺在物流分揀自動化係統中的應用
.net麵試題大全(有答案)
SNMP 簡單網絡管理協議
TraceView性能分析工具介紹
中國航天大事:構建北鬥衛星導航係統
When does the Oracle library for st_shapelib.dll need to be changed?
J2EE的web.xml中filter-mapping的位置導致的亂碼問題
阿裏雲ECS服務器搭建wordpress個人博客網站【詳細圖文教程】