public Bitmap getBitmapFromURL(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap imageBitmap = BitmapFactory.decodeStream(inputStream);
return imageBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
I use this function to get image from url as a bitmap. For a large image bitmap return null. How can ı solve this?
CodePudding user response:
try this bro
private Bitmap getBitmap(String image_link)
{
URL website;
try {
website = new URL(image_link);
HttpURLConnection connection = (HttpURLConnection) website.openConnection();
InputStream is = connection.getInputStream();
if(req_width == 0)
{
return BitmapFactory.decodeStream(is);
}
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);
is.close();
connection = (HttpURLConnection) website.openConnection();
is = connection.getInputStream();
options.inSampleSize = calculateInSampleSize(options, req_width, req_height);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(is, null , options);
} catch (Exception e) {
return null;
}
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
CodePudding user response:
Code modified. See if this works If the bitmap is null, this code will replace it with another sample bitmap.
public Bitmap getBitmapFromURL(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap imageBitmap = BitmapFactory.decodeStream(inputStream);
if(bitmap == null){
imageBitmap =
BitmapFactory.decodeResource(context.getResources(),R.drawable.your_sample_image);
return imageBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}