How to convert an image from URL to Drawable - android

I'm having a problem converting an image to a Drawable object. I'm converting the image using:
public 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;
}
}
I'm trying to put the Drawable in a HashMap and insert that into a ListAdapter, however the value of the Drawable always is something like android.graphics.drawable.BitmapDrawable#405359b0 instead of an integer and I get the message in logcat
resolveUri failed on bad bitmap uri".
this is how I put the Drawable in the HashMap:
map.put("cover", String.valueOf(
Main.this.LoadImageFromWebOperations("http://www.asdfasfs.com/dasfas.jpg")));

Why do you expect the drawable to be an integer? It is an object you can assign to an imageView.
There are items in your project you can refer to with their ID, that is true, but that is something else.
R.drawable.icon is not a Drawable, in the same sense that R.view.your_Button is not a Button. You would call something like getViewFromId() on that. If you have a function that works like this:
doSomethingWithView(R.view.id);
Then it would not work with (pseudocode ofcourse)
myView = new Button();
doSomethingWithView(myView);
So if your function works with a R.drawable.id, it is highly unlikely that it works with a Drawable (except with overloading ofcourse).

Related

how do I transform a string of url's into drawable?

I currently have an arraylist as follows:
private void loadImages() {
images = new ArrayList<>();
images.add(getResources().getDrawable(R.drawable.imag1));
images.add(getResources().getDrawable(R.drawable.imag2));
images.add(getResources().getDrawable(R.drawable.imag3));
}
I want to be able to convert a url into these drawables such that:
drawable1 = "http.someimage.com/image.png"
drawable2 = "http.someimage.com/newimage.png"
followed by
private void loadImages() {
images = new ArrayList<>();
images.add(getResources().getDrawable(drawable1));
images.add(getResources().getDrawable(drawable2));
...etc }
Is there any easy way to go around this? I definitely want to stick to drawables ,but I cant find any way to convert a url to drawable
Any ideas? Thanks!
If you have a URL of the picture you need to download it first.
You can't "convert" a URL into a drawable.
you need something like this:
URL url = new URL("http.someimage.com/image.png");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
Then if you need to add the image into an ImageView object you can call the method .setImageBitmap(bmp).
Otherwise there are ways to extract a Drawable object from the Bitmap
you can check this previous answer. then once you have the drawable you can add it to your arraylist.
Hope I got your question right
P.S.: be sure not to do this on main thread since it is a network operation! use a thread or an asynctask

How to check android drawable type?

Can I check the type of drawable at runtime whether it is an xml shape/selector/layer-list or jpg/png/gif file?
You can get type of drawable with this:
public static String getTypeOfDrawable(int drawableId,Context context) {
Drawable resImg = context.getResources().getDrawable(drawableId);
return resImg.getClass().toString().replace("class android.graphics.drawable.","");
}
You will get result like:
BitmapDrawable
StateListDrawable
Then you if it is BitmapDrawable its not that hard to get format of file

Retrieve only one image with Html.ImageGetter?

Iv'e been using the ImageGetter() interface in the Html.fromHtml() to retrieve image urls from a long html String. But since I only really need one image I don't want to go through the entire String and look for images. I would simply like to stop when I find the first image.
Any suggestions?
Html.fromHtml(html, new ImageGetter() {
#Override
public Drawable getDrawable(String source) {
item.setImageUrl(source);
return null;
}
}, null);
EDIT : for now I only retrieve the last image in the html String so the ImageGetter will only retrieve that image.
private String getLastImage(String htmlContent){
String img = "";
try{
img = htmlContent.substring(htmlContent.lastIndexOf("<img"));
}catch (Exception e) {
e.printStackTrace();
}
return img;
}
Have a boolean field in your ImageGetter. In getDrawable(), fetch the image only if the boolean is false and then set it to true; return null otherwise.
To completely avoid parsing the rest of the HTML, you can not use Html.fromHtml(). Instead you may try using XMLPullParser. Just keep pulling tags until you get an <img> tag, at which point get the value of its <src> attribute.
But you may have to handle inputs which are not strict XHTML properly.

Display image from URL - sizing and screen orientation problems

I am trying to display an image from a URL, which may be larger than the screen dimensions. I have it kind of working, but I would like it to scale to fit the screen, and I also have problems when the screen orientation changes. The image is tiny, and I would like it to scale its width to the screen as well. (In both cases, I would like the image to fill the screen width with scrollbars (if necessary for height).
Here is my ImageView:
<ImageView android:id="#+id/ImageView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:adjustViewBounds="true">
</ImageView>
Here is the java code which loads the image: (some error handling code removed for simplicity)
Object content = null;
try{
URL url = new URL("http://farm1.static.flickr.com/150/399390737_7a3d508730_b.jpg");
content = url.getContent();
}
catch(Exception ex)
{
ex.printStackTrace();
}
InputStream is = (InputStream)content;
Drawable image = Drawable.createFromStream(is, "src");
Image01.setImageDrawable(image);
I have tried different settings for android:scaleType. I'm sorry if this question has been asked before. I've gone through a number of tutorials on the subject, but they don't seem to work for me. Not sure if it has anything to do with the way the image is loaded. (from the web instead of a local resource)
Another issue is that sometimes the image doesn't even load. There are no runtime errors, I just get nothing in the ImageView.
Please let me know if you need more information or clarification.
the issue about that "sometimes the image doesn't even load" is related to the context so I used this functions to solve that issue
public Object fetch(String address) throws MalformedURLException,
IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
private Drawable ImageOperations(Context ctx, String url) {
try {
InputStream is = (InputStream) this.fetch(url);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
}
}
so to fill the screen width with your image you must have a code like this
try{
String url = "http://farm1.static.flickr.com/150/399390737_7a3d508730_b.jpg";
Drawable image =ImageOperations(this,url);
Image01.setImageDrawable(image);
}
catch(Exception ex)
{
ex.printStackTrace();
}
Image01.setMinimumWidth(width);
Image01.setMinimumHeight(height);
Image01.setMaxWidth(width);
Image01.setMaxHeight(height);
UPDATE::
if you load a big size image obviously you will have to wait more time, and download problems could be caused for UnknowHostException.
yes you are right you will save your image locally, the local access is faster than the download.
to avoid problems on rotation change set your configChanges="keyboardHidden|orientation" property inside your Manifest.xml
<activity android:name=".myActivity"
...
android:configChanges="keyboardHidden|orientation" >
...
/>

Need suggestion about a mixed "Uri / int id" images ambient

I have the following problem:
suppose that until now, I am using R.drawable.img to set the image in some imageviews
with
imgView.setImage(aProduct.getImgId());
the simplified product class look like this:
class Product{
int imgId;
....
public void setImgId(int id){
this.imgId=id;
}
public int getImgId(){
return this.imgId
}
...
}
my application is now "evolved" because the user can add customized products
taking the img from the camera and getting the Uri of the picture.
and to set the image on the ImageView imgView.setImgURI(Uri)
Now my question is:
what would be the best approach to have a mixed int/Uri image resources ambient?
can I obtain the Uri of a "R.drawable.img"?
I'm not sure if my question is clear, I mean:
I have to check, before to set the imageview, if my product has an Uri or an int Id,
and then make an "if" to call the appropriate method, or there is a simpler solution?
Thank you for reading, and sorry for my english.
Regards.
Your problem is that there are basically 3 types of image resources:
R.id... resources: internal resources, such as icons you put into the res folder
content URI's: local files or content provider resources such as content:// or file:///sdcard/...
remote file URL's: images on the web, such as http://...
You are looking for a way to pass around one identifier that can deal with all three. My solution was to pass around a string: either the toString() of the URI's, or just the string respresentation of the R.id integer.
I'm using the following code, for example, to deal with this and make the code work with it:
public static FastBitmapDrawable returnAndCacheCover(String cover, ImageRepresentedProductArtworkCreator artworkCreator) {
Bitmap bitmap = null;
Uri coverUri = null;
boolean mightBeUri = false;
//Might be a resId. Needs to be cached. //TODO: problem: resId of default cover may not survive across versions of the app.
try {
bitmap = BitmapFactory.decodeResource(Collectionista.getInstance().getResources(), Integer.parseInt(cover));
} catch (NumberFormatException e) {
//Not a resId after all.
mightBeUri=true;
}
if(bitmap==null || mightBeUri){
//Is not a resId. Might be a contentUri.
try {
coverUri = Uri.parse(cover);
} catch (NullPointerException ne) {
//Is null
return null;
}
}
if(coverUri!=null){
if(coverUri.getScheme().equals("content")){
//A contentUri. Needs to be cached.
try {
bitmap = MediaStore.Images.Media.getBitmap(Collectionista.getInstance().getContentResolver(), coverUri);
} catch (FileNotFoundException e) {
return null;
} catch (IOException e) {
return null;
}
}else{
//Might be a web uri. Needs to be cached.
bitmap = loadCoverFromWeb(cover);
}
}
return new FastBitmapDrawable(bitmap);
}
You might be interested to take over the logic part. Ofcourse cover is the string in question here.
Forget android.resource:// as a replacement for the R.id... integer. Claims are going round it does not work: http://groups.google.com/group/android-developers/browse_thread/thread/a672d71dd7df4b2d
To find out how to implement loadCoverFromWeb, have a look around in other questions or ping me. This web stuff is kind of a field of it's own.
(Based on GPLv3 code out of my app Collectionista: https://code.launchpad.net/~pjv/collectionista/trunk)

Categories

Resources