Created
April 28, 2016 23:55
-
-
Save FlaviusPopescu/a742d548e4d2eeb35e9757258c9e780e to your computer and use it in GitHub Desktop.
Internet and Background Threads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ImageUtil { | |
private static final String TAG = "ImageUtil"; | |
public static Bitmap getImage(String urlSpec) { | |
Bitmap result = null; | |
try { | |
byte[] posterBytes = getBytes(urlSpec); | |
result = BitmapFactory.decodeByteArray(posterBytes, 0, posterBytes.length); | |
} catch (IOException e) { | |
Log.e(TAG, "getImage: ", e); | |
} | |
return result; | |
} | |
private static byte[] getBytes(String urlSpec) throws IOException { | |
URL url = null; | |
try { | |
url = new URL(urlSpec); | |
} catch (MalformedURLException e) { | |
e.printStackTrace(); | |
} | |
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); | |
try { | |
ByteArrayOutputStream out = new ByteArrayOutputStream(); | |
InputStream in = conn.getInputStream(); | |
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { | |
return null; | |
} | |
byte[] buffer = new byte[1024]; | |
int byteCount; | |
while ((byteCount = in.read(buffer)) > 0) { | |
out.write(buffer, 0, byteCount); | |
} | |
out.close(); | |
return out.toByteArray(); | |
} finally { | |
conn.disconnect(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment