setImageResource vs setImageURI - android

I want to get the photo from internet so I use setImageURI, but it seems can't be done, but if I use setImageResource(R.drawable.) under the same function, it works... How could I fix the setImageURI's error?
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
//this is working
int p = R.drawable.fb;
i.setImageResource(p);
//this is not working
i.setImageURI(Uri.parse("http://www.vaultads.com/wp-content/uploads/2011/03/google-adsense.jpg"));
return i;
}

wan to get the photo from internet so i use setImageURI, but it seems
cant be done, but while if i use setImageResource(R.drawable.)
The most most important thing
setImageResource is synchronous so it will execute correctly but setImageURI from URL is asynchronous operation and it must be performed in separate thread than UI thread
Following Snippet will help you.
new Thread() {
public void run() {
try {
url = new URL("http://www.vaultads.com/wp-content/uploads/2011/03/google-adsense.jpg");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
image = BitmapFactory.decodeStream(url.openStream());
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
i.setImageBitmap(image);
}
});
}
}.start();
In case that too don't work then You have three other options
Option1
URL myUrl = new URL("http://www.vaultads.com/wp-content/uploads/2011/03/google-adsense.jpg");
InputStream inputStream = (InputStream)myUrl.getContent();
Drawable drawable = Drawable.createFromStream(inputStream, null);
i.setImageDrawable(drawable);
Option2
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://www.vaultads.com/wp-content/uploads/2011/03/google-adsense.jpg").getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Option3
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
i.setImageBitmap(loadBitmap("http://www.vaultads.com/wp-content/uploads/2011/03/google-adsense.jpg"));

That image URL doesn't work for me.
I would recommend going another route for downloading an image from the internet. If you call setImageURI from getView it will be running on the UI thread, which will cause your app to freeze until the image is returned from the network. Also, the image won't be cached so you could potentially download the same image over and over.
Check out this ImageLoader library for Android which can simplify downloading images. It handles downloading them in the background, it can process multiple request simultaneously, and it caches images for you.

Related

get raw file data from url and display in ImageView

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

load image from URL and save on memory in android

How to load image from URL and save that on memory of device in android? Dont say me use Picasso or oser laibrary.
I need to:
If device get internet conection I load image to ImageView from url and save it on memory of device, else I need to load one of save image to imageView. Thank`s for helps
P.S. Sorry me, I can make some mistakes in question because I don`t very good know English.
This my class:
public class ImageManager {
String file_path;
Bitmap bitmap = null;
public Bitmap donwoaledImageFromSD() {
File image = new File(Environment.getExternalStorageDirectory().getPath(),file_path);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
return bitmap;
}
private void savebitmap() {
File file = new File("first");
file_path = file.getAbsolutePath();
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90,fileOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
public void fetchImage(final String url, final ImageView iView) {
new AsyncTask<String, Void, Bitmap>() {
protected Bitmap doInBackground(String... iUrl) {
try {
InputStream in = new URL(url).openStream();
bitmap = BitmapFactory.decodeStream(in);
savebitmap();
} catch (Exception e) {
donwoaledImageFromSD();
}
return bitmap;
}
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (iView != null) {
iView.setImageBitmap(result);
}
}
}.execute(url);
}
}
Try to use this code:
Method for loading image from imageUrl
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;
}
}
And You should use it in a separate thread, like that:
new Thread(new Runnable() {
#Override
public void run() {
try {
Bitmap bitmap = getBitmapFromURL(<URL of your image>);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
}
}).start();
But using Picasso - indeed a better way.
Update:
For saving Bitmap to file on external storage (SD card) You can use method like this:
public static void writeBitmapToSD(String aFileName, Bitmap aBitmap) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return;
}
File sdPath = Environment.getExternalStorageDirectory();
File sdFile = new File(sdPath, aFileName);
if (sdFile.exists()) {
sdFile.delete ();
}
try {
FileOutputStream out = new FileOutputStream(sdFile);
aBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
}
}
Remember that You need
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
for it.
And for loading `Bitmap` from file on external storage You can use method like that:
public static Bitmap loadImageFromSD(String aFileName) {
Bitmap result = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
try {
FileInputStream fis = new FileInputStream(new File(Environment.getExternalStorageDirectory(), aFileName));
result = BitmapFactory.decodeStream(fis);
fis.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "loadImageFromSD: " + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
You need
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
to do this.
Update 2
Method getBitmapFromURL(), but ImageView should be updated from UI thread, so You should call getBitmapFromURL(), for example, this way:
new Thread(new Runnable() {
#Override
public void run() {
try {
final Bitmap bitmap = getBitmapFromURL("<your_image_URL>");
runOnUiThread(new Runnable() {
#Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
}
}).start();
I had this same issue and I hope this helps. First, To download Image from URL into your app, use the code below:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
In order for the image to be displayed inside the app, use the method below in your onCreate method:
new DownloadImageTask((ImageView) -your imageview id-)
.execute(-your URL-);
In order for the image to be saved INTERNALLY inside the app/phone, use the code below:
#SuppressLint("WrongThread")
protected void onPostExecute(Bitmap result) {
if (result != null) {
File dir = new File(peekAvailableContext().getFilesDir(), "MyImages");
if(!dir.exists()){
dir.mkdir();
}
File destination = new File(dir, "image.jpg");
try {
destination.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(destination);
fos.write(bitmapdata);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
bmImage.setImageBitmap(result);
}
}
To load the image from the internal storage, use the code below:
private void loadImageFromStorage(String path)
{
try {
File f=new File(path, "image.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView img=(ImageView)findViewById(R.id.businessCard_iv);
img.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
Things to note: 1. path is the a string containing the path of the file. 2. "image.jpg" is the file name so ensure that matches with yours. 3. "MyImages" is a folder in your path which contains the actual saved image.

BitmapFactory returns null though there exist an image

Here I want to convert an image from String URL. Though there is an URL containing image, it returns null. I have shared code below.
private byte[] convertImageToByteArray(String imgPath)
{
byte[] byteArray = null;
Bitmap bmp = BitmapFactory.decodeFile(imgPath);
if(bmp != null)
{
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
//bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
try
{
stream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
else
{
try {
Bitmap bmpDefault = BitmapFactory.decodeResource(getResources(), R.drawable.na);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
//bmpDefault.compress(Bitmap.CompressFormat.JPEG, 100, stream);
bmpDefault.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
}
catch (Exception e)
{
e.printStackTrace();
}
}
return byteArray;
}
Instead of executing if block, the control flow enters into else block and BitmapFactory.decodeFile() always returns null. Where I went wrong?
Ravindra's answer is helpful, for better utilization of image try Picasso lib,is mind blowing. It has also resize/crop method.
Picasso.with(getContext()).load("your url").into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
//do what ever you want with your bitmap
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
You can use this reference, it might be helpfull to you.
Note :- This function makes Network Connection, you should call it inside thread or AsyncTask. Otherwise it might throw NetworkOnMainThread Exception.
As the function is returning Bitmap, you will have to wait till your thread is executed so check this question.
which uses join()
I hope this helps.
Use these lines of code for it:-
Bitmap bmImg;
AsyncTask<String, String, String> _Task = new AsyncTask<String, String, String>()
{
#Override
protected void onPreExecute()
{
String _imgURL = "**HERE IS YOUR URL OF THE IMAGE**";
}
#Override
protected String doInBackground(String... arg0)
{
HttpGet httpRequest = new HttpGet(URI.create(_imgURL));
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
bmImg = BitmapFactory.decodeStream(bufHttpEntity.getContent());
System.out.println("main url"+mainUrl);
httpRequest.abort();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result)
{
try
{
/////HERE USE YOURS BITMAP
**bmImg** is your bitmap , you can use it any where i your class
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
_Task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

Dynamically populate Android ImageView with outside resources

How can I turn the static image
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.67"
android:src="#drawable/static_image" />
into an ImageView whose source can be dynamically set to data that is not already in the res folder?
That is, my application has an icon on the screen but the actual image for the icon is downloaded from an outside server and can change dynamically. How do I update the ImageView with the desired image upon download? I want something functionally like:
Image selectedImage = //get from server
myImageView.setImage(selectedImage);
Ur question is not clear. If u just wanna have an image(that is in some url) set to an image view,
Bitmap bmp=getBitmapFromURL(ur url here);
imgview.setImageBitmap(bmp);
and write this function:
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 (Exception ex) {
return null;
}
yourImageView.setImageBitmap(bitmap);
to get Bitmap from server:
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
As per I understand your question something like,
ImageView selectedImage;
selectedImage = (ImageView)findViewById(R.id.imageView1);
Bitmap bmImg;
downloadFile(imageUrl);
And this is downloadFile() Method...
void downloadFile(String fileUrl){
URL myFileUrl =null;
try {
myFileUrl= new URL(fileUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
selectedImage.setImageBitmap(bmImg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You need to create a custom view and over-ride onDraw(). From there you are provided the drawing Canvas and you can do whatever you like. So assuming your dynamic image can be converted to a bitmap, there are numerous drawBitmap() methods you can use from Canvas.
Note that you must also override onMeasure() which allows your view to tell the layout manager how much space you need.
There's a lot of good info here:
http://developer.android.com/guide/topics/ui/custom-components.html

How can I fetch a large image from a url?

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();
}
}
}

Categories

Resources