How to download a image from URL in App - android

I'd like to know how I can download an Image from a given URL and display it inside an ImageView. And is there any permissions required to mention in the manifest.xml file?

You need to put this permission to access the Internet
<uses-permission android:name="android.permission.INTERNET" />
you can try this code.
String imageurl = "YOUR URL";
InputStream in = null;
try
{
Log.i("URL", imageurl);
URL url = new URL(imageurl);
URLConnection urlConn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.connect();
in = httpConn.getInputStream();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
Bitmap bmpimg = BitmapFactory.decodeStream(in);
ImageView iv = "YOUR IMAGE VIEW";
iv.setImageBitmap(bmpimg);

Use background thread to get image and after getting image set it in imageview using hanndler.
new Thread(){
public void run() {
try {
Bitmap bitmap = BitmapFactory.decodeStream(new URL("http://imageurl").openStream());
Message msg = new Message();
msg.obj = bitmap;
imageHandler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
Handler code where we set downloaded image in imgaeview.
Handler imageHandler = new Handler(){
public void handleMessage(Message msg) {
if(msg.obj!=null && msg.obj instanceof Bitmap){
imageview.setBackgroundDrawable(new BitmapDrawable((Bitmap)msg.obj));
}
};
};
And ofcourse you need internet permission.
<uses-permission android:name="android.permission.INTERNET" />

You need to set usage permission of INTERNET in android manifest file and use java.net.URL and java.net.URLConnection classes to request the URL.

There is the BitmapFactory-class which can do that. It can create a Bitmap-object from an InputStream, which can then be displayed in an ImageView.
Something you should know is, that using a normal URLConnection to get an InputStream on a URL-object does not always work with the bitmap-factory. A work-around is presented here: Android: Bug with ThreadSafeClientConnManager downloading images

look this:
Option A:
public static Bitmap getBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(new FlushedInputStream(is));
bis.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return bm;
}
Option B:
public 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);
input.close();
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Jus run the method in a background thread.

Related

get a Bitmap Image from given URL shows java.io.FileNotFoundException

In my android project I would like to get a Bitmap image from given URL(htp://....) for this purpose I have used the below code to achieve this concept. But while running my code I am getting java.io.FileNotFoundException. So anyone please provide a better solution to solve this issue or else provide any code snippet to achieve this task.
public static Bitmap getBitmapFromURL(String src) {
try {
Log.e("src", src);
String stringURL = "http://.....";
URL url = new URL(stringURL);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap", "returned");
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("Exception", e.getMessage());
return null;
}
}

Image not showing on image view

I am trying to set image on imageview but image is not show.
I am reading image url from json data and then trying to set it on ImageView but my image is not visible. No any exception occur.
Here is my code
HotelList.class
static final String TAG_DISHIMAGEURL = "dishimageurl";
......
String imageUrl = dishResult.getString(TAG_DISHIMAGEURL);
map.put(TAG_DISHIMAGEURL, imageUrl);
.....
dishimageurl1 = hm.get(TAG_DISHIMAGEURL).toString();
intent.putExtra("background", dishimageurl1);
HotelDetails.class
......
String dishimageurl = bundle.getString("background");
Bitmap bimage= getBitmapFromURL(dishimageurl);
imageView.setImageBitmap(bimage);
....
public Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
Toast.makeText(this, "showing image", Toast.LENGTH_LONG).show();
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
Toast.makeText(this, "showing exception", Toast.LENGTH_LONG).show();
return null;
}
}
I don't understand what happen with this code. No any exception but my image is not visible.
Please give me any reference.
Please Use below code for get image from url and display into imageview.
public class image extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bitmap bitmap = DownloadImage("http://www.gophoto.it/view.php?i=http://1.bp.blogspot.com/-2LTvCCufBKc/T3L3KgcTj2I/AAAAAAAABbQ/Ki60e1LU9sE/s1600/Sachin%2BTendulkar.png");
RelativeLayout mRlayout1 = (RelativeLayout) findViewById(R.id.mRlayout1);
Drawable d=new BitmapDrawable(bitmap);
mRlayoutLogin.setBackgroundDrawable(d);
}
private InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
}
you can view image by using this code.
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It seems you are downloading the image from UI thread. this will block the UI thread and will give you not responding error. as an easy way, you can use a library like Universal Image Loader
Universal Image Loader - GitHub
this will manage the image loading for you and avoid problems like incorrect urls, Out Of Memory error.

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 read an image from a URL in Android?

I want to read an image from a this URL photo
and I'm using the following code
public static Bitmap DownloadImage(String URL)
{
Bitmap bitmap=null;
InputStream in=null;
try {
in=networking.OpenHttpConnection("http://izwaj.com/"+URL);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=8;
bitmap=BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (Exception e) {
// TODO: handle exception
}
return bitmap;
}
public class Networking {
public InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in=null;
int response = -1;
URL url=new URL(urlString);
URLConnection conn=url.openConnection();
if(!(conn instanceof HttpURLConnection))
{
throw new IOException("Not an HTTP connection");
}
try {
HttpURLConnection httpconn=(HttpURLConnection)conn;
httpconn.setAllowUserInteraction(false);
httpconn.setInstanceFollowRedirects(true);
httpconn.setRequestMethod("GET");
httpconn.connect();
response=httpconn.getResponseCode();
if(response==HttpURLConnection.HTTP_OK)
{
in=httpconn.getInputStream();
}
}
catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
The bitmap always returned to me null.. I used also other functions found on the internet. all returned the bitmap as null value :S
use this function it may help you.
public Bitmap convertImage(String url)
{
URL aURL = null;
try
{
final String imageUrl =url.replaceAll(" ","%20");
Log.e("Image Url",imageUrl);
aURL = new URL(imageUrl);
URLConnection conn = aURL.openConnection();
InputStream is = conn.getInputStream();
//#SuppressWarnings("unused")
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(new PatchInputStream(bis));
if(bm==null)
{}
else
Bitmap bit=Bitmap.createScaledBitmap(bm,72, 72, true);//mention size here
return bit;
}
catch (IOException e)
{
Log.e("error in bitmap",e.getMessage());
return null;
}
}
I would check the %20 spacing on the picture
http://184.173.7.132/RealAds_Images/Apartment%20for%20sale,%20Sheikh%20Zayed%20_%201.jpg
To me the %20 will not render a space so ensure this is noted in your code
if you change the file to apartmentforsalesheikhzayed20201.jpg or something like as a test apartment.jpg it will work.
Personally instead of using spaces in your image names i would use an underscore between the spaces so no other code is needed try_renaming_your_photo_to_this.jpg :)

Android imageview only accepts some jpg's

I have an image view in my app. when I try to make it show a jpg file exported from 3ds max, it works. But if it comes from Photoshop, it just does nothing. Why is that? If it is at all important my app gets the image from my server with the following code:
public static Bitmap getWebImage(String URL)
{
URL myImageURL = null;
Bitmap bitmap = null;
try {
myImageURL = new URL(URL);
} catch (MalformedURLException error) {
error.printStackTrace();
}
try {
HttpURLConnection connection = (HttpURLConnection)myImageURL .openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
Can you check the color settings of your JPG files? Most likely your JPG files from photoshop is in CMYK rather than RGB, and Android simply doesn't support CMYK.
Would it be possible for you to upload the two pictures for comparison?
public static Bitmap getWebImage(String URL)
{
URL myImageURL = null;
Bitmap bitmap = null;
try {
myImageURL = new URL(URL);
} catch (MalformedURLException error) {
error.printStackTrace();
}
try {
HttpURLConnection connection = (HttpURLConnection)myImageURL .openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}

Categories

Resources