这里我正在尝试将我的图片网址转换为位图,以便我可以在网格视图中显示。 log.d部分工作正常,我成功地以字符串格式获取我的图像网址,但是当遇到解码流部分时,它发生了错误。
public class StringtoBitmap extends AsyncTask<String, String, Bitmap> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(Bitmap s) {
super.onPostExecute(s);
}
@Override
protected Bitmap doInBackground(String... params) {
try {
String src = params[0];
Log.d("SRC", src);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
input.reset();
return myBitmap;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
public void StringtoBitmap(String img) {
new StringtoBitmap().execute(img);
}
}
android监视器结果的某些部分:
05-09 02:56:21.408 11585-11671/com.comma.androidapp1 E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
Process: com.comma.androidapp1, PID: 11585
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
at android.graphics.BitmapFactory.decodeStreamInternal(BitmapFactory.java:613)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:589)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:627)
at com.comma.androidapp1.StringtoBitmap.doInBackground(StringtoBitmap.java:39)
at com.comma.androidapp1.StringtoBitmap.doInBackground(StringtoBitmap.java:17)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
[ 05-09 02:56:21.418 1556: 1711 D/ ]
HostConnection::get() New Host Connection established 0xb86734b0, tid 1711
答案 0 :(得分:0)
你出现内存不足的错误,你的位图大小很大,下面的代码解决了内存不足的错误
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap preview_bitmap = BitmapFactory.decodeStream(is, null, options);
答案 1 :(得分:0)