Search in sources :

Example 41 with Image

use of com.codename1.ui.Image in project CodenameOne by codenameone.

the class CodenameOneImplementation method openGallery.

/**
 * Opens the device gallery
 * The method returns immediately and the response will be sent asynchronously
 * to the given ActionListener Object
 *
 * use this in the actionPerformed to retrieve the file path
 * String path = (String) evt.getSource();
 *
 * @param response a callback Object to retrieve the file path
 * @param type one of the following GALLERY_IMAGE, GALLERY_VIDEO, GALLERY_ALL
 * @throws RuntimeException if this feature failed or unsupported on the platform
 */
public void openGallery(final ActionListener response, int type) {
    final Dialog d = new Dialog("Select a picture");
    d.setLayout(new BorderLayout());
    FileTreeModel model = new FileTreeModel(true);
    if (type == Display.GALLERY_IMAGE) {
        model.addExtensionFilter("jpg");
        model.addExtensionFilter("png");
    } else if (type == Display.GALLERY_VIDEO) {
        model.addExtensionFilter("mp4");
        model.addExtensionFilter("3pg");
        model.addExtensionFilter("avi");
        model.addExtensionFilter("mov");
    } else if (type == Display.GALLERY_ALL) {
        model.addExtensionFilter("jpg");
        model.addExtensionFilter("png");
        model.addExtensionFilter("mp4");
        model.addExtensionFilter("3pg");
        model.addExtensionFilter("avi");
        model.addExtensionFilter("mov");
    }
    FileTree t = new FileTree(model) {

        protected Button createNodeComponent(final Object node, int depth) {
            if (node == null || !getModel().isLeaf(node)) {
                return super.createNodeComponent(node, depth);
            }
            Hashtable t = (Hashtable) Storage.getInstance().readObject("thumbnails");
            if (t == null) {
                t = new Hashtable();
            }
            final Hashtable thumbs = t;
            final Button b = super.createNodeComponent(node, depth);
            b.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent evt) {
                    response.actionPerformed(new ActionEvent(node, ActionEvent.Type.Other));
                    d.dispose();
                }
            });
            final ImageIO imageio = ImageIO.getImageIO();
            if (imageio != null) {
                Display.getInstance().scheduleBackgroundTask(new Runnable() {

                    public void run() {
                        byte[] data = (byte[]) thumbs.get(node);
                        if (data == null) {
                            ByteArrayOutputStream out = new ByteArrayOutputStream();
                            try {
                                imageio.save(FileSystemStorage.getInstance().openInputStream((String) node), out, ImageIO.FORMAT_JPEG, b.getIcon().getWidth(), b.getIcon().getHeight(), 1);
                                data = out.toByteArray();
                                thumbs.put(node, data);
                                Storage.getInstance().writeObject("thumbnails", thumbs);
                            } catch (IOException ex) {
                                Log.e(ex);
                            }
                        }
                        Image im = Image.createImage(data, 0, data.length);
                        b.setIcon(im);
                    }
                });
            }
            return b;
        }
    };
    d.addComponent(BorderLayout.CENTER, t);
    d.placeButtonCommands(new Command[] { new Command("Cancel") });
    Command c = d.showAtPosition(2, 2, 2, 2, true);
    if (c != null) {
        response.actionPerformed(null);
    }
}
Also used : Hashtable(java.util.Hashtable) ActionEvent(com.codename1.ui.events.ActionEvent) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ImageIO(com.codename1.ui.util.ImageIO) FileTreeModel(com.codename1.components.FileTreeModel) BorderLayout(com.codename1.ui.layouts.BorderLayout) ActionListener(com.codename1.ui.events.ActionListener) FileTree(com.codename1.components.FileTree)

Example 42 with Image

use of com.codename1.ui.Image in project CodenameOne by codenameone.

the class CodenameOneImplementation method downloadImageToCache.

/**
 * Downloads an image from a URL to the cache. Platforms
 * that support a native image cache {@link #supportsNativeImageCache() } (e.g. Javascript) override this method to defer to the
 * platform's handling of cached images.  Platforms that have a caches directory ({@link FileSystemStorage#hasCachesDir() }
 * will use that directory to cache the image.  Other platforms will just download to storage.
 *
 * @param url The URL of the image to download.
 * @param onSuccess Callback on success.
 * @param onFail Callback on fail.
 *
 * @see URLImage#createToCache(com.codename1.ui.EncodedImage, java.lang.String, com.codename1.ui.URLImage.ImageAdapter)
 */
public void downloadImageToCache(String url, SuccessCallback<Image> onSuccess, final FailureCallback<Image> onFail) {
    FileSystemStorage fs = FileSystemStorage.getInstance();
    if (fs.hasCachesDir()) {
        String name = "cn1_image_cache[" + url + "]";
        name = StringUtil.replaceAll(name, "/", "_");
        name = StringUtil.replaceAll(name, "\\", "_");
        name = StringUtil.replaceAll(name, "%", "_");
        name = StringUtil.replaceAll(name, "?", "_");
        name = StringUtil.replaceAll(name, "*", "_");
        name = StringUtil.replaceAll(name, ":", "_");
        name = StringUtil.replaceAll(name, "=", "_");
        String filePath = fs.getCachesDir() + fs.getFileSystemSeparator() + name;
        // We use Util.downloadImageToFileSystem rather than CodenameOneImplementation.downloadImageToFileSystem
        // because we want it to try to load from file system first.
        Util.downloadImageToFileSystem(url, filePath, onSuccess, onFail);
    } else {
        // We use Util.downloadImageToStorage rather than CodenameOneImplementation.downloadImageToStorage
        // because we want it to try to load from storage first.
        Util.downloadImageToStorage(url, "cn1_image_cache[" + url + "]", onSuccess, onFail);
    }
}
Also used : FileSystemStorage(com.codename1.io.FileSystemStorage)

Example 43 with Image

use of com.codename1.ui.Image in project CodenameOne by codenameone.

the class ImageDownloadService method createImageToFileSystem.

/**
 * Constructs an image request that will automatically populate the given list
 * when the response arrives, it will cache the file locally as a file
 * in the file storage.
 * This assumes the GenericListCellRenderer style of
 * list which relies on a map based model approach.
 *
 * @param url the image URL
 * @param targetList the list that should be updated when the data arrives
 * @param targetOffset the offset within the list to insert the image
 * @param targetKey the key for the map in the target offset
 * @param destFile local file to store the data into the given path
 */
private static void createImageToFileSystem(final String url, final Component targetList, final ListModel targetModel, final int targetOffset, final String targetKey, final String destFile, final Dimension toScale, final byte priority, final Image placeholderImage, final boolean maintainAspectRatio) {
    if (Display.getInstance().isEdt()) {
        Display.getInstance().scheduleBackgroundTask(new Runnable() {

            public void run() {
                createImageToFileSystem(url, targetList, targetModel, targetOffset, targetKey, destFile, toScale, priority, placeholderImage, maintainAspectRatio);
            }
        });
        return;
    }
    // image not found on cache go and download from the url
    ImageDownloadService i = new ImageDownloadService(url, targetList, targetOffset, targetKey);
    i.targetModel = targetModel;
    i.maintainAspectRatio = maintainAspectRatio;
    Image im = cacheImage(null, false, destFile, toScale, placeholderImage, maintainAspectRatio);
    if (im != null) {
        i.setEntryInListModel(targetOffset, im);
        targetList.repaint();
        return;
    }
    i.cacheImages = true;
    i.destinationFile = destFile;
    i.toScale = toScale;
    i.placeholder = placeholderImage;
    i.setPriority(priority);
    i.setFailSilently(true);
    NetworkManager.getInstance().addToQueue(i);
}
Also used : EncodedImage(com.codename1.ui.EncodedImage) Image(com.codename1.ui.Image) FileEncodedImage(com.codename1.components.FileEncodedImage) StorageImage(com.codename1.components.StorageImage)

Example 44 with Image

use of com.codename1.ui.Image in project CodenameOne by codenameone.

the class ImageDownloadService method postResponse.

/**
 * {@inheritDoc}
 */
protected void postResponse() {
    // trigger an exception in case of an invalid image
    result.getWidth();
    Image image = result;
    if (toScale != null && toScale.getWidth() != image.getWidth() && toScale.getHeight() != image.getHeight()) {
        image = scaleImage(image, toScale, maintainAspectRatio);
    }
    final Image i = image;
    if (parentLabel != null) {
        final Dimension pref = parentLabel.getPreferredSize();
        if (parentLabel.getComponentForm() != null) {
            Display.getInstance().callSerially(new Runnable() {

                public void run() {
                    if (isDownloadToStyles()) {
                        parentLabel.getUnselectedStyle().setBgImage(i);
                        parentLabel.getSelectedStyle().setBgImage(i);
                        parentLabel.getPressedStyle().setBgImage(i);
                    } else {
                        parentLabel.setIcon(i);
                    }
                    Dimension newPref = parentLabel.getPreferredSize();
                    // sized image in place or has a hardcoded preferred size.
                    if (pref.getWidth() != newPref.getWidth() || pref.getHeight() != newPref.getHeight()) {
                        parentLabel.getComponentForm().revalidate();
                    }
                }
            });
        } else {
            Display.getInstance().callSerially(new Runnable() {

                public void run() {
                    if (isDownloadToStyles()) {
                        parentLabel.getUnselectedStyle().setBgImage(i);
                        parentLabel.getSelectedStyle().setBgImage(i);
                        parentLabel.getPressedStyle().setBgImage(i);
                    } else {
                        parentLabel.setIcon(i);
                    }
                }
            });
        }
        parentLabel.repaint();
        return;
    } else {
        if (targetList != null) {
            setEntryInListModel(targetOffset, image);
            // revalidate only once to avoid multiple revalidate refreshes during scroll
            if (targetList.getParent() != null) {
                if (alwaysRevalidate) {
                    targetList.getParent().revalidate();
                } else {
                    if (targetList.getClientProperty("$imgDSReval") == null) {
                        targetList.putClientProperty("$imgDSReval", Boolean.TRUE);
                        targetList.getParent().revalidate();
                    } else {
                        targetList.repaint();
                    }
                }
            }
        }
    }
    // if this is a list cell renderer component
    fireResponseListener(new NetworkEvent(this, result));
}
Also used : NetworkEvent(com.codename1.io.NetworkEvent) Dimension(com.codename1.ui.geom.Dimension) EncodedImage(com.codename1.ui.EncodedImage) Image(com.codename1.ui.Image) FileEncodedImage(com.codename1.components.FileEncodedImage) StorageImage(com.codename1.components.StorageImage)

Example 45 with Image

use of com.codename1.ui.Image in project CodenameOne by codenameone.

the class ContactsModel method getContactAsHashtable.

private Hashtable getContactAsHashtable(Contact c) {
    Hashtable table = new Hashtable();
    String id = null;
    String fname;
    String lname;
    String displayName;
    Image image;
    String phone;
    String email;
    if (c == null) {
        fname = "Loading...";
        lname = "Loading...";
        displayName = "Loading...";
        image = placeHolder;
        phone = "Loading...";
        email = "Loading...";
    } else {
        id = c.getId();
        fname = c.getFirstName();
        lname = c.getFamilyName();
        displayName = c.getDisplayName();
        image = c.getPhoto();
        if (image == null) {
            image = placeHolder;
        }
        phone = getContactPhoneNumber(c);
        email = getContactEmail(c);
    }
    addAttribute(table, "id", id);
    addAttribute(table, "fname", fname);
    addAttribute(table, "lname", lname);
    addAttribute(table, "displayName", displayName);
    addAttribute(table, "icon", image);
    addAttribute(table, "phone", phone);
    addAttribute(table, "email", email);
    // something is missing there is the ability to get the Contact.
    if (c != null) {
        table.put("contact", c);
    }
    return table;
}
Also used : Hashtable(java.util.Hashtable) Image(com.codename1.ui.Image)

Aggregations

Image (com.codename1.ui.Image)82 EncodedImage (com.codename1.ui.EncodedImage)46 IOException (java.io.IOException)29 Hashtable (java.util.Hashtable)19 AnimationObject (com.codename1.ui.animations.AnimationObject)18 BufferedImage (java.awt.image.BufferedImage)18 Style (com.codename1.ui.plaf.Style)16 Form (com.codename1.ui.Form)15 ActionEvent (com.codename1.ui.events.ActionEvent)14 Dimension (com.codename1.ui.geom.Dimension)14 FontImage (com.codename1.ui.FontImage)13 BorderLayout (com.codename1.ui.layouts.BorderLayout)13 Timeline (com.codename1.ui.animations.Timeline)12 ActionListener (com.codename1.ui.events.ActionListener)12 Border (com.codename1.ui.plaf.Border)12 Container (com.codename1.ui.Container)11 InputStream (java.io.InputStream)11 Graphics (com.codename1.ui.Graphics)10 Label (com.codename1.ui.Label)10 Button (com.codename1.ui.Button)9