在做android项目时,我们经常需要从本地或者网络读取图片,并转换为Bitmap图片,以便使用,下面是读取本地图片并转换的方法:
- /**
- * 得到本地或者网络上的bitmap url - 网络或者本地图片的绝对路径,比如:
- *
- * A.网络路径: 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;
- }
- }
附加的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);
}
}原文:http://blog.youkuaiyun.com/jdsjlzx/article/details/7578311