问题
I need to make a new Image instance from a string that has the url of the image.
E.g. http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png
This type of urls come from a JSONParser and I want to use them to populate the icons of a multibutton list.
I use the following getItemAt method of this Model class put data on a multibutton list. Each multibutton has an icon and some lines. I have named Line1 as name and Line2 as rating. I want from the string url to make an Image so I can change the multibutton icon in place of defaultIcon in h.put("icon", defaultIcon) line.
static class Model implements ListModel {
public Object getItemAt(int index) {
Hashtable h = new Hashtable();
Hashtable entry = (Hashtable) results.elementAt(index);
String name = (String) entry.get("name");
Double rating = (Double) entry.get("rating");
String url = (String) entry.get("icon");
h.put("name", name);
h.put("icon", defaultIcon); // change defaultIcon with an Image from url String
if (rating == null) {
h.put("rating", "Not rated");
} else {
h.put("rating", "Rating: " + rating.toString());
}
return h;
}
回答1:
Use ImageDownloadService.createImageToStorage
which will asynchronously download the image, place it in the Hashtable for the list in the proper location. Refresh the list and cache the image in storage in case you ask for it again.
It can also scale your image to a fixed dimension as part of the service.
回答2:
You can use this to obtain an image from an url
Image image = Toolkit.getDefaultToolkit().getDefaultToolkit().createImage(url);
this could also work
Image image = ImageIO.read(url);
来源:https://stackoverflow.com/questions/12979247/how-to-create-an-image-from-a-url-codenameone