Skip to content

Instantly share code, notes, and snippets.

@FlaviusPopescu
Created April 28, 2016 23:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FlaviusPopescu/a742d548e4d2eeb35e9757258c9e780e to your computer and use it in GitHub Desktop.
Save FlaviusPopescu/a742d548e4d2eeb35e9757258c9e780e to your computer and use it in GitHub Desktop.
Internet and Background Threads
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