在做android項目時,我們經(jīng)常需要從本地或者網(wǎng)絡(luò)讀取圖片,并轉(zhuǎn)換為Bitmap圖片,以便使用,下面是讀取本地圖片并轉(zhuǎn)換的方法:
Java代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
/** * 得到本地或者網(wǎng)絡(luò)上的bitmap url - 網(wǎng)絡(luò)或者本地圖片的絕對路徑,比如: * * A.網(wǎng)絡(luò)路徑: url="http://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 是一個常量而已,可以改成常數(shù),比如2*1024,其實取決于你的圖片大小,自己根據(jù)圖片的大小自己設(shè)定吧。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。