Skip to content

Instantly share code, notes, and snippets.

@truongngoclinh
Last active January 18, 2017 09:12
Show Gist options
  • Save truongngoclinh/2c4ba2b546a4efb4f7f98a9afcdfaa50 to your computer and use it in GitHub Desktop.
Save truongngoclinh/2c4ba2b546a4efb4f7f98a9afcdfaa50 to your computer and use it in GitHub Desktop.
Get bitmap from url, scale down by set BitmapOptions.
private Bitmap getBitmapFromUrl(String src) {
if (!TextUtils.isEmpty(src)) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap;
if (inputStream.markSupported()) {
Log.d(TAG, "getBitmapFromUrl: markSuported = true, mark and reset stream to reuse");
inputStream.mark(inputStream.available());
BitmapFactory.decodeStream(inputStream, null, options);
options.inSampleSize = calculateInSampleSize(options, ScreenUtils.getPx(140), ScreenUtils.getPx(200));
options.inJustDecodeBounds = false;
inputStream.reset();
bitmap = BitmapFactory.decodeStream(inputStream, null, options);
} else {
Log.d(TAG, "getBitmapFromUrl: markSuported = false");
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
data = buffer.toByteArray();
buffer.flush();
Log.d(TAG, "getBitmapFromUrl: byte array size = " + data.length);
BitmapFactory.decodeByteArray(data, 0, data.length, options);
options.inSampleSize = calculateInSampleSize(options, ScreenUtils.getPx(140), ScreenUtils.getPx(200));
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
}
inputStream.close();
return bitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
private int calculateInSampleSize(BitmapFactory.Options options, int reqHeight, int reqWidth) {
Log.d(TAG, "calculateInSampleSize: options: " + options.outWidth + ", " + options.outHeight + " req: " + reqWidth + ", " + reqHeight);
final int height = options.outHeight;
final int width = options.outWidth;
int sampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / sampleSize) >= reqHeight
&& (halfWidth / sampleSize) >= reqWidth) {
sampleSize *= 2;
}
}
Log.d(TAG, "calculateInSampleSize: " + sampleSize);
return sampleSize;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment