Convert image URL to drawable resource id in android - android

I'm using the KenBurnsView library with this code:
mHeaderPicture.setResourceIds(R.drawable.picture0, R.drawable.picture1);
As you can see it takes drawable resource ids.
What I want to do is covert all photos URLS to drawable resource ids.
Photo urls like this:
http://example.com/image.jpg
http://example.com/image2.jpg
http://example.com/image3.jpg
http://example.com/image4.jpg
I tried this code here and it didn't work:
Bitmap drawable_from_url(String url) throws java.net.MalformedURLException, java.io.IOException {
Bitmap x;
HttpURLConnection connection = (HttpURLConnection)new URL(url) .openConnection();
connection.setRequestProperty("User-agent","Mozilla/4.0");
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return x;
}
I have read a LOT of questions and answers all over the web and I didn't find a good tutorial or solution.

Try to drop this library into your project. Its a useful library.
http://square.github.io/picasso/
Sample Usage:
Picasso.with(context).load("http://example.com/image.jpg").into(imageView);
How to get the drawable from imageView:
Drawable myDrawable = imageView.getDrawable();

You can't convert a Bitmap to a resource id. Resource ids are only for resources in your APK. You'll have to edit or extend the KenBurnsView class to accept Bitmap objects e.g by adding a function like this:
public void setBitmaps(Bitmap... bitmaps) {
for (int i = 0; i < mImageViews.length; i++) {
mImageViews[i].setImageBitmap(bitmaps[i]);
}
}
Then you can pass the Bitmaps that you load with drawable_from_url()

You just forgot to add setDoInput to connection
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);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}

Add asynchronous task ...
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
.execute(url);
}
public void onClick(View v) {
startActivity(new Intent(this, IndexActivity.class));
finish();
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView mHeaderPicture;
public DownloadImageTask(ImageView mHeaderPicture){
this.mHeaderPicture= mHeaderPicture;
} 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;
}
protected void onPostExecute(Bitmap result) {
mHeaderPicture.setImageBitmap(result);
}
}`
Make sure you have the following permissions set in your AndroidManifest.xml to access the internet.
<uses-permission android:name="android.permission.INTERNET" />

Related

Don't display the Image Fetch From URL online Android

I want to show an image from online (url) but it shows me nothing and i don't know why this happens. I add INTERNET permission in manifest also.
private ImageView iv;
private Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String address = "http://4.bp.blogspot.com/-3_EM3_dBstc/UxD7U2EEa2I/AAAAAAAACmI/M9JilH6eIV0/s100/Krita-logo.png";
iv = (ImageView) findViewById(R.id.image);
bitmap = bitImageRead(address);
iv.setImageBitmap(bitmap);
}
Where i do wrong?
Try this..
public Bitmap bitImageRead(address){
try {
URL url = new URL(address);
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;
}
}

Load image larger than 2048x2048 into ImageView on Android

I need to load high res remote images to imageview, but without using any external libraries or frameworks. Images are like 2150x1500 px, and here is my code for loading:
URL imageUrl = new URL(url);
HttpURLConnection connection;
if (url.startsWith("https://")) {
connection = (HttpURLConnection) imageUrl.openConnection();
} else {
connection = (HttpURLConnection) imageUrl.openConnection();
}
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setInstanceFollowRedirects(true);
InputStream is = connection.getInputStream();
OutputStream os = new FileOutputStream(f);
CacheUtils.CopyStream(is, os);
os.close();
image = decodeFile(f);
img.setImageBitmap(image);
and here is decodeFile function:
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
and I always get texture size too big exception. Is there any way to load these images? Or is there a way to resize image not 2 or 4 times, but resize to fit 2048 pixels by width?
class DownloadImage extends AsyncTask<String, Void, Bitmap>
{
ImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = bmImage;
}
#Override
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;
}
#Override
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(Bitmap.createScaledBitmap(result, 120, 120, false));
}
}
Specify the height and width you need instead of 120.
Call this in your oncreate
new DownloadImage((ImageView) findViewById(R.id.imageView1))
.execute("https://.........");

Why can't I retrieve FaceBook profile pic in Android?

I am trying to retrieve my FaceBook Profile pic using a Url in Android. I am not able to retrieve any image. I have no error logs as such but I get the following Log.
04-05 04:14:41.005: D/skia(2987): --- SkImageDecoder::Factory returned null. I am posting the codes. Please tell me step by step what am I doing wrong.
final ImageView photoImageView=(ImageView)findViewById(R.id.imageView1);
AsyncTask<Void, Void, Bitmap> t = new AsyncTask<Void, Void, Bitmap>(){
protected Bitmap doInBackground(Void... p) {
Bitmap bm = null;
try {
URL aURL = new URL("http://graph.facebook.com/+"id"+/picture?type=small");
URLConnection conn = aURL.openConnection();
conn.setUseCaches(true);
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
// photoImageView.setImageBitmap(bm);
} catch (IOException e) {
e.printStackTrace();
}
return bm;
}
protected void onPostExecute(Bitmap bm){
// Drawable drawable = new BitmapDrawable(getResources(), bm);
photoImageView.setImageBitmap(bm);
// photoImageView.setBackgroundDrawable(drawable);
}
};
t.execute();
Try this below code, This is perfectly working for me.
try {
URL image_value = new URL("http://graph.facebook.com/"+ user.getId()+ "/picture?type=large");
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(image_value.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
profile_pic.setImageBitmap(bmp);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL aURL = new URL("https://graph.facebook.com/"+id+"/picture?type=small");
Try this.
And if id is integer convert to string
And also not http , try https

Android 4.0.4 Show Image From Remote Url?

I am trying to show an Image from remote URL using ImageView control
private Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}
catch (Exception e) {
System.out.println("Exc="+e);
return null;
}
}
Set Image :
Drawable drawable = LoadImageFromWebOperations(Manager.URL());
imageView.setBackgroundDrawable(drawable);
It's working in android 2.2 and 3.2 but not working in android 4.0.4?
Tanks .
My problem was resolved by this code
public class DownloadImagesTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
return download_Image(urls[0]);
}
#Override
protected void onPostExecute(Bitmap result) {
_imgview.setImageBitmap(result); // how do I pass a reference to mChart here ?
}
private Bitmap download_Image(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(bis);
bis.close();
is.close();
} catch (IOException e) {
}
return bm;
//---------------------------------------------------
}
}
and use in activity :
new DownloadImagesTask().execute(url));

How to load an ImageView by URL in Android?

How do you use an image referenced by URL in an ImageView?
From Android developer:
// show The Image in a ImageView
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
.execute("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
public void onClick(View v) {
startActivity(new Intent(this, IndexActivity.class));
finish();
}
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;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
Make sure you have the following permissions set in your AndroidManifest.xml to access the internet.
<uses-permission android:name="android.permission.INTERNET" />
1. Picasso allows for hassle-free image loading in your application—often in one line of code!
Use Gradle:
implementation 'com.squareup.picasso:picasso:(insert latest version)'
Just one line of code!
Picasso.get().load("http://i.imgur.com/DvpvklR.png").into(imageView);
2. Glide An image loading and caching library for Android focused on smooth scrolling
Use Gradle:
repositories {
mavenCentral()
google()
}
dependencies {
implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
}
// For a simple view:
Glide.with(this).load("http://i.imgur.com/DvpvklR.png").into(imageView);
3. fresco is a powerful system for displaying images on Android applications. Fresco takes care of image loading and display, so you don't have to.
Getting Started with Fresco
You'll have to download the image firstly
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;
}
Then use the Imageview.setImageBitmap to set bitmap into the ImageView
Anyway people ask my comment to post it as answer. i am posting.
URL newurl = new URL(photo_url_str);
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());
profile_photo.setImageBitmap(mIcon_val);
I wrote a class to handle this, as it seems to be a recurring need in my various projects:
https://github.com/koush/UrlImageViewHelper
UrlImageViewHelper will fill an
ImageView with an image that is found
at a URL.
The sample will do a Google Image
Search and load/show the results
asynchronously.
UrlImageViewHelper will automatically
download, save, and cache all the
image urls the BitmapDrawables.
Duplicate urls will not be loaded into
memory twice. Bitmap memory is managed
by using a weak reference hash table,
so as soon as the image is no longer
used by you, it will be garbage
collected automatically.
The accepted answer above is great if you are loading the image based on a button click, however if you are doing it in a new activity it freezes up the UI for a second or two. Looking around I found that a simple asynctask eliminated this problem.
To use an asynctask add this class at the end of your activity:
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;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
And call from your onCreate() method using:
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
.execute(MY_URL_STRING);
The result is a quickly loaded activity and an imageview that shows up a split second later depending on the user's network speed.
You could also use this LoadingImageView view to load an image from a url:
http://blog.blundellapps.com/imageview-with-loading-spinner/
Once you have added the class file from that link you can instantiate a url image view:
in xml:
<com.blundell.tut.LoaderImageView
android:id="#+id/loaderImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
image="http://developer.android.com/images/dialog_buttons.png"
/>
In code:
final LoaderImageView image = new LoaderImageView(this, "http://developer.android.com/images/dialog_buttons.png");
And update it using:
image.setImageDrawable("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
The best modern library for such a task in my opinion is Picasso by Square. It allows to load an image to an ImageView by URL with one-liner:
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
public class LoadWebImg extends Activity {
String image_URL=
"http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView bmImage = (ImageView)findViewById(R.id.image);
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
Bitmap bm = LoadImage(image_URL, bmOptions);
bmImage.setImageBitmap(bm);
}
private Bitmap LoadImage(String URL, BitmapFactory.Options options)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bitmap;
}
private InputStream OpenHttpConnection(String strURL) throws IOException{
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try{
HttpURLConnection httpConn = (HttpURLConnection)conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
}
catch (Exception ex)
{
}
return inputStream;
}
}
Hi I have the most easiest code try this
public class ImageFromUrlExample extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView imgView =(ImageView)findViewById(R.id.ImageView01);
Drawable drawable = LoadImageFromWebOperations("http://www.androidpeople.com/wp-content/uploads/2010/03/android.png");
imgView.setImageDrawable(drawable);
}
private Drawable LoadImageFromWebOperations(String url)
{
try{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e) {
System.out.println("Exc="+e);
return null;
}
}
}
main.xml
<LinearLayout
android:id="#+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="#+id/ImageView01"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
try this
I have recently found a thread here, as I have to do a similar thing for a listview with images, but the principle is simple, as you can read in the first sample class shown there (by jleedev).
You get the Input stream of the image (from web)
private InputStream fetch(String urlString) throws MalformedURLException, IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
return response.getEntity().getContent();
}
Then you store the image as Drawable and you can pass it to the ImageView (via setImageDrawable). Again from the upper code snippet take a look at the entire thread.
InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");
Lots of good info in here...I recently found a class called SmartImageView that seems to be working really well so far. Very easy to incorporate and use.
http://loopj.com/android-smart-image-view/
https://github.com/loopj/android-smart-image-view
UPDATE: I ended up writing a blog post about this, so check it out for help on using SmartImageView.
2ND UPDATE: I now always use Picasso for this (see above) and highly recommend it. :)
This is a late reply, as suggested above AsyncTask will will and after googling a bit i found one more way for this problem.
Drawable drawable = Drawable.createFromStream((InputStream) new URL("url").getContent(), "src");
imageView.setImageDrawable(drawable);
Here is the complete function:
public void loadMapPreview () {
//start a background thread for networking
new Thread(new Runnable() {
public void run(){
try {
//download the drawable
final Drawable drawable = Drawable.createFromStream((InputStream) new URL("url").getContent(), "src");
//edit the view in the UI thread
imageView.post(new Runnable() {
public void run() {
imageView.setImageDrawable(drawable);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
Don't forget to add the following permissions in your AndroidManifest.xml to access the internet.
<uses-permission android:name="android.permission.INTERNET" />
I tried this myself and i have not face any issue yet.
imageView.setImageBitmap(BitmapFactory.decodeStream(imageUrl.openStream()));//try/catch IOException and MalformedURLException outside
This will help you...
Define imageview and load image into it .....
Imageview i = (ImageView) vv.findViewById(R.id.img_country);
i.setImageBitmap(DownloadFullFromUrl(url));
Then Define this method :
public Bitmap DownloadFullFromUrl(String imageFullURL) {
Bitmap bm = null;
try {
URL url = new URL(imageFullURL);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
bm = BitmapFactory.decodeByteArray(baf.toByteArray(), 0,
baf.toByteArray().length);
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
return bm;
}
String img_url= //url of the image
URL url=new URL(img_url);
Bitmap bmp;
bmp=BitmapFactory.decodeStream(url.openConnection().getInputStream());
ImageView iv=(ImageView)findviewById(R.id.imageview);
iv.setImageBitmap(bmp);
Version with exception handling and async task:
AsyncTask<URL, Void, Boolean> asyncTask = new AsyncTask<URL, Void, Boolean>() {
public Bitmap mIcon_val;
public IOException error;
#Override
protected Boolean doInBackground(URL... params) {
try {
mIcon_val = BitmapFactory.decodeStream(params[0].openConnection().getInputStream());
} catch (IOException e) {
this.error = e;
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean success) {
super.onPostExecute(success);
if (success) {
image.setImageBitmap(mIcon_val);
} else {
image.setImageBitmap(defaultImage);
}
}
};
try {
URL url = new URL(url);
asyncTask.execute(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
private Bitmap getImageBitmap(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(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e(TAG, "Error getting bitmap", e);
}
return bm;
}
A simple and clean way to do this is to use the open source library Prime.
This code is tested, it is completely working.
URL req = new URL(
"http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png"
);
Bitmap mIcon_val = BitmapFactory.decodeStream(req.openConnection()
.getInputStream());
Working for imageView in any container , like listview grid view , normal layout
private class LoadImagefromUrl extends AsyncTask< Object, Void, Bitmap > {
ImageView ivPreview = null;
#Override
protected Bitmap doInBackground( Object... params ) {
this.ivPreview = (ImageView) params[0];
String url = (String) params[1];
System.out.println(url);
return loadBitmap( url );
}
#Override
protected void onPostExecute( Bitmap result ) {
super.onPostExecute( result );
ivPreview.setImageBitmap( result );
}
}
public Bitmap loadBitmap( String url ) {
URL newurl = null;
Bitmap bitmap = null;
try {
newurl = new URL( url );
bitmap = BitmapFactory.decodeStream( newurl.openConnection( ).getInputStream( ) );
} catch ( MalformedURLException e ) {
e.printStackTrace( );
} catch ( IOException e ) {
e.printStackTrace( );
}
return bitmap;
}
/** Usage **/
new LoadImagefromUrl( ).execute( imageView, url );
Try this way,hope this will help you to solve your problem.
Here I explain about how to use "AndroidQuery" external library for load image from url/server in asyncTask manner with also cache loaded image to device file or cache area.
Download "AndroidQuery" library from here
Copy/Paste this jar to project lib folder and add this library to project build-path
Now I show demo to how to use it.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imageFromUrl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"/>
<ProgressBar
android:id="#+id/pbrLoadImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</FrameLayout>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
private AQuery aQuery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
aQuery = new AQuery(this);
aQuery.id(R.id.imageFromUrl).progress(R.id.pbrLoadImage).image("http://itechthereforeiam.com/wp-content/uploads/2013/11/android-gone-packing.jpg",true,true);
}
}
Note : Here I just implemented common method to load image from url/server but you can use various types of method which can be provided by "AndroidQuery"to load your image easily.
Android Query can handle that for you and much more (like cache and loading progress).
Take a look at here.
I think is the best approach.

Categories

Resources