How to create an Image from a url Codenameone

依然范特西╮ 提交于 2019-12-22 12:05:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!