I previously worked on fetching image from sd card displaying it in a list view, that worked using:
imgView.setImageURI(Uri.parse(ImagePath));
Now, I am trying to display image from URL, with the following lines but the image is not displayed in the list view, the following are the lines used:
imgView.setImageBitmap(getBitmapFromURL(ImagePath));
Where, getBitmapFromURL is:
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) {
e.printStackTrace();
return null;
}
}
There is no exception displayed, the image just not get displayed.
Need of an urgent solution....
Thanks,
This is a synchronous loading.(Personally I would not use this cause if there are so many Image to be loaded, the apps is a bit laggy)..
URL url = new URL(//your URL);
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);//your imageview
If I were you I would study Async or the lazy adapter..
EDIT
I forgot where I got these code (well thank you for a wonderful code author)
Here it is
public Bitmap getBitmap(String bitmapUrl) {
try {
URL url = new URL(bitmapUrl);
return BitmapFactory.decodeStream(url.openConnection().getInputStream());
}
catch(Exception ex) {return null;}
}
public enum BitmapManager {
INSTANCE;
private final Map<String, SoftReference<Bitmap>> cache;
private final ExecutorService pool;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
private Bitmap placeholder;
BitmapManager() {
cache = new HashMap<String, SoftReference<Bitmap>>();
pool = Executors.newFixedThreadPool(5);
}
public void setPlaceholder(Bitmap bmp) {
placeholder = bmp;
}
public Bitmap getBitmapFromCache(String url) {
if (cache.containsKey(url)) {
return cache.get(url).get();
}
return null;
}
public void queueJob(final String url, final ImageView imageView,
final int width, final int height) {
/* Create handler in UI thread. */
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
String tag = imageViews.get(imageView);
if (tag != null && tag.equals(url)) {
if (msg.obj != null) {
imageView.setImageBitmap((Bitmap) msg.obj);
} else {
imageView.setImageBitmap(placeholder);
Log.d(null, "fail " + url);
}
}
}
};
pool.submit(new Runnable() {
public void run() {
final Bitmap bmp = downloadBitmap(url, width, height);
Message message = Message.obtain();
message.obj = bmp;
Log.d(null, "Item downloaded: " + url);
handler.sendMessage(message);
}
});
}
public void loadBitmap(final String url, final ImageView imageView,
final int width, final int height) {
imageViews.put(imageView, url);
Bitmap bitmap = getBitmapFromCache(url);
// check in UI thread, so no concurrency issues
if (bitmap != null) {
Log.i("inh","Item loaded from cache: " + url);
imageView.setImageBitmap(bitmap);
} else {
imageView.setImageBitmap(placeholder);
queueJob(url, imageView, width, height);
}
}
private Bitmap downloadBitmap(String url, int width, int height) {
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
url).getContent());
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
Log.i("nandi2 ako", ""+bitmap);
cache.put(url, new SoftReference<Bitmap>(bitmap));
return bitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Now to call it
String fbAvatarUrl = "//Your URL";
BitmapManager.INSTANCE.loadBitmap(fbAvatarUrl, //Your ImageView, 60,60);
//60 60 is my desired height and width
I encountered this kind problem before, you can refer to this thread, if no luck, try my code,
public static Bitmap loadImageFromUrl(String url) {
URL m;
InputStream i = null;
BufferedInputStream bis = null;
ByteArrayOutputStream out =null;
try {
m = new URL(url);
i = (InputStream) m.getContent();
bis = new BufferedInputStream(i,1024 * 8);
out = new ByteArrayOutputStream();
int len=0;
byte[] buffer = new byte[1024];
while((len = bis.read(buffer)) != -1){
out.write(buffer, 0, len);
}
out.close();
bis.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
byte[] data = out.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
return bitmap;
}
Related
I would like to display an image from the URL that is providing me raw data for the image(png or JPG).
I checked this link but not much useful.
Here is my image link
I am processing the raw data but could not see the image. I am not sure how do I check that I got the right raw data.
here is my effort
private class DownloadImageTask extends AsyncTask<String, Void, Void> {
byte[] bytes;
Bitmap picture = null;
#Override
protected Void doInBackground(String... urls) {
// final OkHttpClient client = new OkHttpClient();
//
// Request request = new Request.Builder()
// .url(urls[0])
// .build();
//
// Response response = null;
//
// try {
// response = client.newCall(request).execute();
// } catch (IOException e) {
// e.printStackTrace();
// }
// assert response != null;
// if (response.isSuccessful()) {
// try {
// assert response.body() != null;
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// IOUtils.copy(response.body().byteStream(), baos);
// bytes = baos.toByteArray();
// picture = BitmapFactory.decodeStream(response.body().byteStream());
// } catch (Exception e) {
// Log.e("Error", Objects.requireNonNull(e.getMessage()));
// e.printStackTrace();
// }
//
// }
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
URL url = new URL(urls[0]);
byte[] chunk = new byte[4096];
int bytesRead;
InputStream stream = url.openStream();
while ((bytesRead = stream.read(chunk)) > 0) {
outputStream.write(chunk, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
bytes = outputStream.toByteArray();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (bytes != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
cameraView.setImageBitmap(bitmap);
}
// cameraView.setImageBitmap(picture);
}
}
The location of your problem/s in your workflow seems ill-determined.
You should first identify this.
(Plus, you did not specify if you are bound to a specific programming language).
For this sake, I suggest you:
Start using a raw image file that you know is correct, and test its processing.
There are quite a few raw image formats.
Judging from the tag android, I guess the following can help:
To capture a raw iamge into a file: How to capture raw image from android camera
To display in ImageView: Can't load image from raw to imageview
https://gamedev.stackexchange.com/questions/14046/how-can-i-convert-an-image-from-raw-data-in-android-without-any-munging
https://developer.android.com/reference/android/graphics/ImageFormat
https://www.androidcentral.com/raw-images-and-android-everything-you-need-know
Try getting a raw image from an URL that you can manage.
Apply this to the actual target URL.
This way you will know where your problem resides.
Without more info it is hard to "debug" your problem.
You can also inspect code in FOSS projects.
You could use a library named Picasso and do the following:
String url = get url from the Async Function and convert it to String
/*if you url has no image format, you could do something like this con convert the uri into a Bitmap*/
public Bitmap getCorrectlyOrientedImage(Context context, Uri uri, int maxWidth)throws IOException {
InputStream input = context.getContentResolver().openInputStream(uri);
BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
onlyBoundsOptions.inJustDecodeBounds = true;
onlyBoundsOptions.inDither = true;//optional
onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
try {
input.close();
} catch (NullPointerException e) {
e.printStackTrace();
}
/*trying to get the right orientation*/
if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1)) {
return null;
}
int originalSize = Math.max(onlyBoundsOptions.outHeight, onlyBoundsOptions.outWidth);
double ratio = (originalSize > maxWidth) ? (originalSize / maxWidth) : 1.0;
Matrix matrix = new Matrix();
int rotationInDegrees = exifToDegrees(orientation);
if (orientation != 0) matrix.preRotate(rotationInDegrees);
int bmpWidth = 0;
try {
assert bitmap != null;
bmpWidth = bitmap.getWidth();
} catch (NullPointerException e) {
e.printStackTrace();
}
Bitmap adjustedBitmap = bitmap;
if (bmpWidth > 0)
adjustedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return adjustedBitmap;
}
/*Then you has the image in Bitmap, you can use the solution below or if Picasso doesn't allows you to put Bitmap you can pass it directly to the ImageView as a Bitmap.*/
ImageView imageView = view.findViewById(R.id.imageViewId);
/*Then use Picasso to draw the image into the ImageView*/
Picasso.with(context).load(url).fit().into(imageView );
This is the dependency for build.gradle, not sure if is the last version but you could try.
implementation 'com.squareup.picasso:picasso:2.5.2'
Kind regards!
Identify the following questions:
Using URL to get bytes to load images
I wrote down what I can with reference to
class DownLoadImageTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
imageView.setImageBitmap(bitmap);
}
#Override
protected Bitmap doInBackground(String... strings) {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(strings[0]).build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
InputStream inputStream = response.body().byteStream();
return BitmapFactory.decodeStream(inputStream);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
This is the URL I use
https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/440px-Image_created_with_a_mobile_phone.png
https://upload.wikimedia.org/wikipedia/commons/3/3a/Cat03.jpg
I can test it. I hope it can help you
My scenario is : I am creating a new bitmap and save to local path then display the image in SimpleDraweeView. If i am using SDV.setImageUri(path) sometimes image is not displayed. So i am using mImageView.setImageDrawable(new BitmapDrawable(mContext.getResources(), bitmap)); . If i am loading next time then ImageView is flickering at the time of loading. I am research about flickering that image is not available in cache that's why its occur. So how can i add image to fersco cache;
You can use fresco to cache existing bitmap
public class DownloadVideoThumbnail extends AsyncTask<String, Void, Bitmap> {
private ImageView bmImage;
private Bitmap bitmapVideo;
private Context context;
public DownloadVideoThumbnail(Context context, ImageView bmImage) {
this.bmImage = (ImageView) bmImage;
this.context = context;
}
protected Bitmap doInBackground(String... urls) {
String urlStr = urls[0];
if (readFromCacheSync(urlStr) == null) {
try {
//Your method call here
bitmapVideo = retriveVideoFrameFromVideo(urlStr);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
} else {
bitmapVideo = readFromCacheSync(urlStr);
}
return null;
}
protected void onPostExecute(Bitmap result) {
if (bitmapVideo != null) {
//Load your bitmap here
bmImage.setImageBitmap(bitmapVideo);
bmImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
}
public void cacheBitmap(Bitmap bitmap, String url) {
try {
CacheKey cacheKey = new SimpleCacheKey(url);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
final byte[] byteArray = stream.toByteArray();
Fresco.getImagePipelineFactory().getMainFileCache().insert(cacheKey, new WriterCallback() {
#Override
public void write(OutputStream outputStream) throws IOException {
outputStream.write(byteArray);
}
});
} catch (IOException cacheWriteException) {
}
}
public static Bitmap readFromCacheSync(String imageUrl) {
CacheKey cacheKey = DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(ImageRequest.fromUri(imageUrl), null);
StagingArea stagingArea = StagingArea.getInstance();
EncodedImage encodedImage = stagingArea.get(cacheKey);
if (encodedImage != null) {
return BitmapFactory.decodeStream(encodedImage.getInputStream());
}
try {
return BitmapFactory.decodeStream(readFromDiskCache(cacheKey));
} catch (Exception e) {
return null;
}
}
private static InputStream readFromDiskCache(final CacheKey key) throws IOException {
try {
FileCache fileCache = ImagePipelineFactory.getInstance().getMainFileCache();
final BinaryResource diskCacheResource = fileCache.getResource(key);
if (diskCacheResource == null) {
FLog.v(TAG, "Disk cache miss for %s", key.toString());
return null;
}
PooledByteBuffer byteBuffer;
final InputStream is = diskCacheResource.openStream();
FLog.v(TAG, "Successful read from disk cache for %s", key.toString());
return is;
} catch (IOException ioe) {
return null;
}
}
public Bitmap retriveVideoFrameFromVideo(String videoPath) throws Throwable {
Bitmap bitmap = null;
MediaMetadataRetriever mediaMetadataRetriever = null;
try {
mediaMetadataRetriever = new MediaMetadataRetriever();
if (Build.VERSION.SDK_INT >= 14)
mediaMetadataRetriever.setDataSource(videoPath, new HashMap<String, String>());
else
mediaMetadataRetriever.setDataSource(videoPath);
bitmap = mediaMetadataRetriever.getFrameAtTime();
if (bitmap != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
cacheBitmap(bitmap, videoPath);
}
} catch (Exception e) {
e.printStackTrace();
throw new Throwable(
"Exception in retriveVideoFrameFromVideo(String videoPath)"
+ e.getMessage());
} finally {
if (mediaMetadataRetriever != null) {
mediaMetadataRetriever.release();
}
}
return bitmap;
}
}
I am creating a to send image from java server to android client.
Here is my android code:
protected Void doInBackground(Void... arg0) {
try {
socket = new Socket("192.168.237.1", 6666);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
// dataOutputStream.writeUTF(textOut.getText().toString());
String base64Code = dataInputStream.readUTF();
Log.d("String", ":" + base64Code);
//
byte[] decodedString;
decodedString = Base64.decode(base64Code);
Log.d("Ds",""+decodedString);
Log.d("St--", ":" + decodedString.length);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inMutable=true;
bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length,options);
Drawable ob=new BitmapDrawable(getResources(),bitmap);
imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setBackgroundDrawable(ob);
/*//imageView.setImageBitmap(bitmap);
ByteArrayInputStream input=new ByteArrayInputStream(decodedString);
bitmap=BitmapFactory.decodeStream(input);
imageView.setImageBitmap(bitmap);*/
Log.d("Bitmap",""+bitmap);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
Log.d("Error", "" + e);
}
}
I have encoded the byte array in java usung apache common codec and decoded in android program.
The error I am getting is it gives NullPointeException at imageView.setBackgroundDrawable (ob);.
What is the error in this code??
You need to do it like this:
private class MyAsyncTask extends AsyncTask<Void, Void, Bitmap> {
#Override
protected Bitmap doInBackground(Void... params) {
try {
socket = new Socket("192.168.237.1", 6666);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
// dataOutputStream.writeUTF(textOut.getText().toString());
String base64Code = dataInputStream.readUTF();
Log.d("String", ":" + base64Code);
//
byte[] decodedString;
decodedString = Base64.decode(base64Code);
Log.d("Ds",""+decodedString);
Log.d("St--", ":" + decodedString.length);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inMutable=true;
bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length,options);
return bitmap;
/*//imageView.setImageBitmap(bitmap);
ByteArrayInputStream input=new ByteArrayInputStream(decodedString);
bitmap=BitmapFactory.decodeStream(input);
imageView.setImageBitmap(bitmap);*/
Log.d("Bitmap",""+bitmap);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
Log.d("Error", "" + e);
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
Drawable ob =new BitmapDrawable(getResources(), bitmap);
imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setBackgroundDrawable(ob);
} else {
// error
}
}
}
You can,t perform UI operations from background thread. They need to be performed in the ui thread. So try and perform thi operationn in onPostExecute().
After seeing all the examples from net, i have written the follwoing code to read an image from the URL, show it to the Image view and save it to the path specified.
public class Downloader {
public void startDownload(ImageView i, String path,String url){
BitmapDownloaderTask task = new BitmapDownloaderTask(i,path);
task.execute(url,null,null);
}
static class FlushedInputStream extends FilterInputStream {
public FlushedInputStream(InputStream inputStream) {
super(inputStream);
}
#Override
public long skip(long n) throws IOException {
long totalBytesSkipped = 0L;
while (totalBytesSkipped < n) {
long bytesSkipped = in.skip(n - totalBytesSkipped);
if (bytesSkipped == 0L) {
int b = read();
if (b < 0) {
break; // we reached EOF
} else {
bytesSkipped = 1; // we read one byte
}
}
totalBytesSkipped += bytesSkipped;
}
return totalBytesSkipped;
}
}
static Bitmap downloadBitmap(String url) {
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
final Bitmap bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// Could provide a more explicit error message for IOException or IllegalStateException
getRequest.abort();
System.err.println("Error while retrieving bitmap from " + url +":"+ e.toString());
} finally {
if (client != null) {
client.close();
}
}
return null;
}
private class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private String url;
private final WeakReference<ImageView> imageViewReference;
private String path;
public BitmapDownloaderTask(ImageView imageView, String FilePath) {
imageViewReference = new WeakReference<ImageView>(imageView);
path = FilePath;
}
#Override
// Actual download method, run in the task thread
protected Bitmap doInBackground(String... params) {
// params comes from the execute() call: params[0] is the url.
return downloadBitmap(params[0]);
}
#Override
// Once the image is downloaded, associates it to the imageView
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
OutputStream outStream = null;
File file = new File(path);
try {
outStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
}
catch(Exception e)
{}
}
}
Now the problem is this code works sometimes and fails sometimes... the error is
06-30 12:34:23.363: WARN/System.err(16360): Error while retrieving bitmap from https://URL IS HERE---REMOVE FOR PRIVACY:java.net.SocketTimeoutException: Read timed out
and some time a get
SkImageDecoder::Factory returned null.
Help me with the possible reason
consider this example its show how to create image from url
URL url = new URL(Your Image URL In String);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
yourImageView.setImageBitmap(myBitmap);
you should implement a retry when the connection was failed.
I used the code below to fetch the image from a url but it doesn't working for large images.
Am I missing something when fetching that type of image?
imgView = (ImageView)findViewById(R.id.ImageView01);
imgView.setImageBitmap(loadBitmap("http://www.360technosoft.com/mx4.jpg"));
//imgView.setImageBitmap(loadBitmap("http://sugardaddydiaries.com/wp-content/uploads/2010/12/how_do_i_get_sugar_daddy.jpg"));
//setImageDrawable("http://sugardaddydiaries.com/wp-content/uploads/2010/12/holding-money-copy.jpg");
//Drawable drawable = LoadImageFromWebOperations("http://www.androidpeople.com/wp-content/uploads/2010/03/android.png");
//imgView.setImageDrawable(drawable);
/* try {
ImageView i = (ImageView)findViewById(R.id.ImageView01);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://sugardaddydiaries.com/wp-content/uploads/2010/12/holding-money-copy.jpg").getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
System.out.println("hello");
} catch (IOException e) {
System.out.println("hello");
}*/
}
protected Drawable ImageOperations(Context context, String string,
String string2) {
// TODO Auto-generated method stub
try {
InputStream is = (InputStream) this.fetch(string);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
You're trying to download the Large Image from within the UI Thread....This will cause an ANR (Application not Responding)
Use AsyncTask to download the images, that way, a seperate thread will be used for the download and your UI Thread wont lock up.
see this good example that loads image from server.
blog.sptechnolab.com/2011/03/04/android/android-load-image-from-url/.
If you want to download the image very quickly then you can use AQuery which is similar to JQuery just download the android-query.0.15.7.jar
Import the jar file and add the following snippet
AQuery aq = new AQuery(this);
aq.id(R.id.image).image("http://4.bp.blogspot.com/_Q95xppgGoeo/TJzGNaeO8zI/AAAAAAAAADE/kez1bBRmQTk/s1600/Sri-Ram.jpg");
// Here R.id.image is id of your ImageView
// This method will not give any exception
// Dont forgot to add Internet Permission
public class MyImageActivity extends Activity
{
private String image_URL= "http://home.austarnet.com.au/~caroline/Slideshows/Butterfly_Bitmap_Download/slbutfly.bmp";
private ProgressDialog pd;
private Bitmap bitmap;
private ImageView bmImage;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bmImage = (ImageView)findViewById(R.id.imageview);
pd = ProgressDialog.show(this, "Please Wait", "Downloading Image");
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { image_URL });
// You can also give more images in string array
}
private class DownloadWebPageTask extends AsyncTask<String, Void, Bitmap>
{
// String --> parameter in execute
// Bitmap --> return type of doInBackground and parameter of onPostExecute
#Override
protected Bitmap doInBackground(String...urls) {
String response = "";
for (String url : urls)
{
InputStream i = null;
BufferedInputStream bis = null;
ByteArrayOutputStream out =null;
// Only for Drawable Image
// try
// {
// URL url = new URL(image_URL);
// InputStream is = url.openStream();
// Drawable d = Drawable.createFromStream(is, "kk.jpg");
// bmImage.setImageDrawable(d);
// }
// catch (Exception e) {
// // TODO: handle exception
// }
// THE ABOVE CODE IN COMMENTS WILL NOT WORK FOR BITMAP IMAGE
try
{
URL m = new URL(image_URL);
i = (InputStream) m.getContent();
bis = new BufferedInputStream(i, 1024*8);
out = new ByteArrayOutputStream();
int len=0;
byte[] buffer = new byte[4096];
while((len = bis.read(buffer)) != -1)
{
out.write(buffer, 0, len);
}
out.close();
bis.close();
byte[] data = out.toByteArray();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
catch (Exception e)
{
e.printStackTrace();
}
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result)
{
if(result!=null)
bmImage.setImageBitmap(result);
pd.dismiss();
}
}
}