2017-11-03 3 views
0

URL에서 비트 맵 객체로 이미지를로드하려고하는데, 항상 NetworkInUIThread 종류의 예외로 끝납니다. 누구든지이 라이브러리를 제공 할 수 있습니까?안드로이드가 URL에서 비트 맵 객체로 이미지로드

ImageView에 이미지를 넣으려고하지 않고 있습니다. 나중에 이미지가 더 많이 사용 될 것이므로, 먼저 Bitmap 객체에 넣고 싶습니다.

이 코드는 다른 StackOverflow 스레드에서 발견되었지만 작동하지 않습니다.

public static Bitmap getBitmapFromURL(String src){ 
    try{ 
     URL url = new URL(src); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.setDoInput(true); 
     connection.connect(); 
     InputStream input = connection.getInputStream(); 
     Bitmap myBitmap = BitmapFactory.decodeStream(input); 
     return myBitmap; 
    }catch(IOException e){ 
     return null; 
    } 
} 
+1

의 사용 가능한 복제 [안드로이드 : AsyncTask를 사용하여 웹에서 이미지를로드 (https://stackoverflow.com/questions/3090650/android

private class MyAsyncTask extends AsyncTask<String, Void, Bitmap> { protected Bitmap doInBackground(String... params) { try { URL url = new URL(params[0]); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap myBitmap = BitmapFactory.decodeStream(input); return myBitmap; } catch(IOException e) { return null; } } protected void onPostExecute(Bitmap result) { //do what you want with your bitmap result on the UI thread } } 

에 의해 활동에 전화 - as-asynctask를 사용하여 웹에서 이미지로드) – nhoxbypass

+0

[android.os.NetworkOnMainThreadException을 어떻게 수정합니까?] (https://stackoverflow.com/questions/6343166/how-do- i-fix-android-os-networkonmiththreadexception) –

+0

처음에는'NetworkOnMainThreadException'에 대해 읽으려고합니다. 개발을 용이하게합니다. –

답변

0
try { 
     URL url = new URL("http://...."); 
     Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream()); 
    } catch(IOException e) { 
     System.out.println(e); 
    } 
1

당신은 서버에서 이미지를 다운로드 및 비트 맵 객체에 저장하기 글라이드를 사용할 수 있습니다

 Bitmap bitmap = null; 
     InputStream iStream = null; 
     URL url = new URL(urlString); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setReadTimeout(5000 /* milliseconds */); 
     conn.setConnectTimeout(7000 /* milliseconds */); 
     conn.setRequestMethod("GET"); 
     conn.setDoInput(true); 
     conn.connect(); 
     iStream = conn.getInputStream(); 
     bitmap = BitmapFactory.decodeStream(iStream); 
1

을 시도합니다.

Bitmap theBitmap = Glide. 
    with(this). 
    load("http://...."). 
    asBitmap(). 
    into(100, 100). // Width and height 
    get(); 

앱에서 글라이드 종속성을 추가하려면이 옵션을 참조하십시오 ->https://github.com/bumptech/glide

+0

'asBitmap'메소드를 사용할 수 없습니다 가장 최근 글라이드 – Matej

+0

참조 http://bumptech.github.io/glide/doc/targets.html –

+0

이미지가 ImageView에로드되는 것을 원하지 않습니다. – Matej

0

AsyncTask

예를 들어,의 doInBackground 방법 내에서이 코드를 넣어

new MyAsyncTask().execute(src); 
+0

이 작업은 가능하지만 비트 맵 결과 개체를 다음과 같이 가져와야합니다. 내 활동. – Matej

+0

그게 당신이 onPostExecute에서해야 할 일입니다 ... MyAsyncTask를 액티비티 내부의 내부 클래스로 생성하십시오. 자세한 내용은 AsyncTask 자습서를 읽으십시오. – pleft