I'm looking for a very basic function. I'm trying to design an app and all I want it to do is load an image from a URL.
I've found a few questions and websites, but they all seem to be older and dated, but what I think I'm having issues with is linking the code to activity main.xml for ImageView.
Any suggestions or links you have I would greatly appreciate, thank you.
Here, this is how I display image from url in the image view
you have to call this code from thread other than main thread
ImageView img = (ImageView) findViewById(R.id.imageView1);
try {
URL url = new URL("Your URL");
//try this url = "http://0.tqn.com/d/webclipart/1/0/5/l/4/floral-icon-5.jpg"
HttpGet httpRequest = null;
httpRequest = new HttpGet(url.toURI());
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient
.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
InputStream input = b_entity.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(input);
img.setImageBitmap(bitmap);
} catch (Exception ex) {
}
Be careful don't forget to surround the code with try catch(I have already done that in this code)
or you can use webview to load image from url
WebView web = (WebView) findViewById(R.id.webView1);
web.loadUrl("Your Url");
if you are trying to load image from the assets folder url will start like this
"file:///android_asset/yourimage.jpg"
else normal internet url like this
"http://0.tqn.com/d/webclipart/1/0/5/l/4/floral-icon-5.jpg"
hope this works for you
Good Luck
There is an opensource library called imageloader. It is widely used, you can use it directly or make code similar to it.
https://github.com/nostra13/Android-Universal-Image-Loader
You can take the image and on your php side convert it into a base64 and then on Android side decode it into a image.
The best practice to download image is to be done on the background Thread, so that it doesn't interrupt your Main Thread,then update the User Interface as needed.
public class MainActivity extends AppCompatActivity {
FrameLayout frameLayout;
ImageView imageView;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout= (FrameLayout) findViewById(R.id.containerlayout);
imageView= (ImageView) findViewById(R.id.imageView);
progressBar= (ProgressBar) findViewById(R.id.progressBar);
String url="http://www.flat-e.com/flate5/wp-content/uploads/cover-960x857.jpg";
MyTask myTask= new MyTask();
myTask.execute(url);
}
class MyTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected Bitmap doInBackground(String... voids) {
Bitmap bitmap=null;
try {
URL url =new URL(voids[0]);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
InputStream inputStream= connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
progressBar.setVisibility(View.GONE);
imageView.setImageBitmap(bitmap);
}
}
}
Here, in this example I created an inner class MyTask which extends the AsyncTask where i have done all my network operations. Make sure to add the Uses permission in your Manifest File.
Hope this works for you too.
Related
i am getting an image url which is protected with password.I know how to do it with the Authenticator but i want to do this with Picasso.
Can anyone please tell me that how to load password protected images to a imageview with Picasso Image loader Library.
Below is the code to do with Authenticator:
private Bitmap download_Image(String url) {
Bitmap bmp = null;
try {
URL ulrn = new URL(url);
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(imagePassword, "mypass".toCharArray());
}
});
HttpURLConnection con = (HttpURLConnection) ulrn.openConnection();
InputStream is = con.getInputStream();
bmp = BitmapFactory.decodeStream(is);
if (null != bmp)
return bmp;
} catch (Exception e) {
e.printStackTrace();
}
return bmp;
}
I believe this is what you're looking for. The post says it could be done using Okhttp.
How to add Basic Authentication in Picasso 2.5.2 with OkHttp 3.2.0
Good luck. :)
Edit
You can set the image to your image view like below.
Picasso.with(context).load("YOUR IMAGE URL HERE").into(imageView);
I want to load an image from a URL but it doesn't work because the link doesn't have an extension
Can this be solved???
URL example :
http://t0.gstatic.com/images?q=tbn:ANd9GcRf1EqE2kyW12HSb9gZZ8eTIPqNgVkjFis4GkTTYONIpoQtkIde4zybZ4iAqGlIHQ_pnEX499Oa
How can this be done??
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView img = (ImageView)findViewById(R.id.imageView1);
Bitmap bitImg = getBitmapFromURL("http://t0.gstatic.com/images?q=tbn:ANd9GcRf1EqE2kyW12HSb9gZZ8eTIPqNgVkjFis4GkTTYONIpoQtkIde4zybZ4iAqGlIHQ_pnEX499Oa");
img.setImageBitmap(bitImg);
}
public Bitmap getBitmapFromURL(String imageUrl) {
try {
URL url = new URL(imageUrl);
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;
}
}
look at this post, i dont see his URL but i think Android libraries figure it out based on the data and headers:
BitmapFactory.decodeStream returning null when options are set
also, don't add an extension to a URL, it changes the URL!
http://www.google.com is not the same as http://www.google.com.html
load an image from a URL but it doesn't work because the link doesn't have an extension. Nonsense. Url.openconnection does not look at extensions. It does not work because you have a NetworkOnMainThreadException clearly visible in the LogCat. Never seen in the LogCat? Please go and look for it. Place your network code in an AsyncTask or thread to prevent this.
I'm trying to get a static image from a map and put on my Android layout. So, looking for it I've found a code talking about Google Static Maps. Awesome! I've tried some URLs on my PC and it's working perfectly!
But my problem was when I've put the URL in Android to test it. WHen I try to get the input stream (the image), it gives me FileNotFoundExceptioin, because when I tried to connect, it threw me a Bad Request (error 400)
Here is my code:
public class ImageLoadingTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... stringURL) {
Bitmap bmp = null;
try {
URL url = new URL(stringURL[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
bmp = BitmapFactory.decodeStream(is, null, options);
} catch (IOException e) {
e.printStackTrace();
}
return bmp;
}
#Override
protected void onPostExecute(Bitmap result) {
mapView.setImageBitmap(result);
super.onPostExecute(result);
}
}
String for test
Do I need a key for this?? Why don't I need a key for doing it in a browser?
The URL you're sending to Google has a strange character in it. Before sending it, run a URLEncode.encode() on it or if you're always showing São Paulo you could say "Sao Paulo" and let Google figure it out, or "S%C3%A3o%20Paulo". Personally I think the first one is less error prone but it's up to you.
I have Multiple images on the server. What I want to do is I want to retrieve these images from the server and set it on the imageView.
I have worked with getting the blob type images from the server, decoding it to byte array and then convert it to Bitmap images.
I am confused about how to get Bitmap images from the server.
I have been through many questions on SO like
Retriving image from server to android app
Load Large Image from server on Android
Please can any one help with a Link or a code.
Thank You for your precious time.
I was trying things and here is the code:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bitmap bitmap = DownloadImage("http://www.allindiaflorist.com/imgs/arrangemen4.jpg");
ImageView img = (ImageView) findViewById(R.id.img);
img.setImageBitmap(bitmap);
}
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);
BufferedInputStream bis = new BufferedInputStream(in, 8190);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
System.out.println("BAF= "+baf);
int current = 0;
while ((current = bis.read()) != -1)
{
baf.append((byte)current);
}
byte[] imageData = baf.toByteArray();
System.out.println("imageData= "+imageData);
bitmap =BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
in.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
return bitmap;
}
}
This returns the image but he url that i have used consists of the image name. What if i have more images and I want to retrieve all of the them as my application loads.
I recommend you a different way that works like a charm: Android Query.
You can download that jar file from here: http://code.google.com/p/android-query/downloads/list
AQuery androidAQuery=new AQuery(this);
As an example:
androidAQuery.id(YOUR IMAGEVIEW).image(YOUR IMAGE TO LOAD, true, true, getDeviceWidth(), ANY DEFAULT IMAGE YOU WANT TO SHOW);
Using above code you can directly show your Image through url. Now below code is to get Bitmap Directly from the url:
androidAQuery.ajax(YOUR IMAGE URL,Bitmap.class,0,new AjaxCallback<Bitmap>(){
#Override
public void callback(String url, Bitmap object, AjaxStatus status) {
super.callback(url, object, status);
//You will get Bitmap from object.
}
});
This library is provided by Android itself, so use it and see the result whatever you want.
It's very fast and accurate, and using this you can find many more features like Animation when loading; getting a bitmap, if needed; etc.
I would recommend you use the Volley library (The presentation is here), the same library used by Google in its application Google Play. At the Google I/O 13, Ficus Kilkpatrick presented Volley. Volley is an HTTP library that aims at removing lots of boilerplate code, simplifying the handling of images in lists, be faster, abstract the complexity of one or another HTTP client.
Initialization
Volley relies on a RequestQueue, that handle a queue of request, and on an ImageLoader, that is in charge of loading the images. We need one of each
public static ImageLoader mImageLoader;
public static RequestQueue mRequestQueue;
We also need to initialize them. The queue needs a Context, the ImageLoader needs an ImageCache. Here, I use a basic wrapper to LruCache.
mRequestQueue = Volley.newRequestQueue(this);
mImageLoader = new ImageLoader(mRequestQueue, new BitmapLru(64000));
The initialization is done in the onCreate() of the first activity.
Getting an image
Suppose you have to fill a gridview with images downloaded from a server. The ImageUrlAdapter populates a GridView (or any AdapterView) with NetworkImageView. This is a class provided by Volley to put images from the network into an ImageView. It actually extends ImageView, meaning you can use it anywhere you use an ImageView. It is extremely simple to use. The only code in the adapter is the getView.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
NetworkImageView imageView;
if (convertView == null) {
imageView = new NetworkImageView(getContext());
} else {
imageView = (NetworkImageView) convertView;
}
String url = getItem(position);
imageView.setImageUrl(url, MainActivity.mImageLoader);
return imageView;
}
The only new thing here is imageView.setImageUrl(url, MainActivity.mImageLoader);
That’s it. Nothing more is required.
Use the Universal Image Loader
Since your confused I'll explain
Download the jar file by clicking here and paste it into your libs folder
In your manifest add these two lines of permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Use this code
ImageLoader imageLoader = ImageLoader.getInstance();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.createDefault(getApplicationContext())
imageLoader.init(config);
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.ic_launcher)
.cacheInMemory()
.cacheOnDisc()
.build();
imageLoader.displayImage("http://www.allindiaflorist.com/imgs/arrangemen4.jpg",your_IMAGEVIEW,options,null);
Or if you just want the bitmap then use this
Bitmap bmp = imageLoader.loadImageSync("http://www.allindiaflorist.com/imgs/arrangemen4.jpg");
I would strongly recommend using the Square's Picasso library. It's very easy to work with and takes away all the pain of retrieving-caching.
I would suggest using Prime Library , it has functioning to download images asynchronously and then a callback with a listener having the url and bitmap image as the parameters.
I have a textView. In my code I am adding some lines of text in it. I also want to display some image from an external URL (not from my resource folder) just in between those lines. Every thing is dynamic i.e. the text generated and the image URL will be generated on the flow.So i have to fetch the image through my code and add it.
Wondering if there is a way to insert images from external URL within text view? Also any better approach is always welcome.
You will have to use this along with asynctask,
open connection in doInbackground()
set image to textview in onPostExecute()
try {
/* Open a new URL and get the InputStream to load data from it. */
URL aURL = new URL("ur Image URL");
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
Drawable d =new BitmapDrawable(bm);
d.setId("1");
textview.setCompoundDrawablesWithIntrinsicBounds(0,0,1,0);// wherever u want the image relative to textview
} catch (IOException e) {
Log.e("DEBUGTAG", "Remote Image Exception", e);
}
hope it helps
You are going to probably want to use an asynctask to grab the image. This will run in the background from your other tasks. Your code may look something like this:
public class ImageDownloader extends AsyncTask<String, Integer, Bitmap>{
private String url;
private final WeakReference<ImageView> imageViewReference;
//a reference to your imageview that you are going to load the image to
public ImageDownloader(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... arg0) {
if(isCancelled())
return null;
Bitmap retVal;
url = arg0[0];//this is the url for the desired image
...download your image here using httpclient or another networking protocol..
return retVal;
}
#Override
protected void onPostExecute(Bitmap result) {
if (isCancelled()) {
result = null;
return;
}
ImageView imageView = imageViewReference.get();
imageView.setImageBitmap(result);
}
#Override
protected void onPreExecute() {
...do any preloading you might need, loading animation, etc...
}