- package com.google.android.panoramio;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.util.Log;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.ByteArrayOutputStream;
- import java.io.Closeable;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.net.URL;
- /**
- * 从指定URL加载位图的工具类
- *
- */
- public class BitmapUtils {
- private static final String TAG = "Panoramio";
- private static final int IO_BUFFER_SIZE = 4 * 1024;
- /**
- * 从指定的url加载位图,这将会持续一段时间,因此不应该从UI线程中调用
- */
- public static Bitmap loadBitmap(String url) {
- Bitmap bitmap = null;
- InputStream in = null;
- BufferedOutputStream out = null;
- try {
- in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
- final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
- out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
- copy(in, out);
- out.flush();
- final byte[] data = dataStream.toByteArray();
- //调用BitmapFactory类的函数从字节数组中解码出位图
- bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
- } catch (IOException e) {
- Log.e(TAG, "Could not load Bitmap from: " + url);
- } finally {
- closeStream(in);
- closeStream(out);
- }
- return bitmap;
- }
- /**
- * 关闭指定的数据流
- */
- private static void closeStream(Closeable stream) {
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException e) {
- android.util.Log.e(TAG, "Could not close stream", e);
- }
- }
- }
- /**
- * 使用临时的字节数组缓存将InputStream中的数据拷贝到OutputStream
- */
- 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);
- }
- }
- }
-
- 从其他博客看到的一段代码,里面的new URL(url).openStream()感觉很便利,记录一下增长下见识
图片的远程加载
最新推荐文章于 2021-07-15 18:20:35 发布