Example usage for android.graphics BitmapFactory decodeStream

List of usage examples for android.graphics BitmapFactory decodeStream

Introduction

In this page you can find the example usage for android.graphics BitmapFactory decodeStream.

Prototype

public static Bitmap decodeStream(InputStream is) 

Source Link

Document

Decode an input stream into a bitmap.

Usage

From source file:com.worklight.poc.Pull.java

public static void updateImageView(final URL url) {
    Runnable run = new Runnable() {
        @Override//ww  w . j  a v a2  s .c om
        public void run() {
            Bitmap bmp;
            try {
                bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
                img.setImageBitmap(bmp);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    _Pull.runOnUiThread(run);
}

From source file:eu.geopaparazzi.library.routing.osmbonuspack.BonusPackHelper.java

/**
 * Loads a bitmap from a url. //from w w w  .j  a  v a 2 s .com
 * @param url
 * @return the bitmap, or null if any issue. 
 */
public static Bitmap loadBitmap(String url) {
    Bitmap bitmap = null;
    try {
        InputStream is = (InputStream) new URL(url).getContent();
        if (is == null)
            return null;
        bitmap = BitmapFactory.decodeStream(new FlushedInputStream(is));
        //Alternative providing better handling on loading errors?
        /*
        Drawable d = Drawable.createFromStream(new FlushedInputStream(is), null);
        if (is != null)
           is.close();
        if (d != null)
           bitmap = ((BitmapDrawable)d).getBitmap();
        */
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return bitmap;
}

From source file:ch.ethz.inf.vs.android.g54.a4.net.RequestHandler.java

/**
 * Downloads image from given URL and converts it to a Bitmap
 * //from w  w  w. j  a v a  2  s  .  c o m
 * @throws ConnectionException
 * @throws UnrecognizedResponseException
 */
public static Bitmap getBitmap(String imageURL) throws ConnectionException, UnrecognizedResponseException {
    Log.d(TAG, "download image from:" + imageURL);

    try {
        URL url = new URL(imageURL);

        // Open a connection to URL
        URLConnection ucon = url.openConnection();

        // Define InputStreams to read from the URLConnection.
        InputStream is = ucon.getInputStream();

        // Read stream into a bitmap
        return BitmapFactory.decodeStream(is);
    } catch (MalformedURLException e) {
        String msg = String.format("Could not resolve url %s.", imageURL);
        throw new ConnectionException(msg, e);
    } catch (IOException e) {
        String msg = String.format("Could not download image from %s.", imageURL);
        throw new UnrecognizedResponseException(msg, e);
    }
}

From source file:com.blueverdi.rosietheriveter.AlbumPageFactory.java

private Bitmap getBitmapFromAssets(String fn) {
    Bitmap bit = null;/*from  w  w w.  ja  va 2  s. com*/
    try {
        InputStream bitmap = context.getAssets().open(fn);
        bit = BitmapFactory.decodeStream(bitmap);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return bit;
}

From source file:com.skalski.raspberrycontrol.Mjpeg.Mjpeg_InputStream.java

public Bitmap readMjpegFrame() throws IOException {
    mark(FRAME_MAX_LENGTH);//w w w .j a  v a2 s.  com
    int headerLen = getStartOfSequence(this, SOI_MARKER);
    reset();
    byte[] header = new byte[headerLen];
    readFully(header);
    try {
        mContentLength = parseContentLength(header);
    } catch (NumberFormatException nfe) {
        mContentLength = getEndOfSeqeunce(this, EOF_MARKER);
    }
    reset();
    byte[] frameData = new byte[mContentLength];
    skipBytes(headerLen);
    readFully(frameData);
    return BitmapFactory.decodeStream(new ByteArrayInputStream(frameData));
}

From source file:nl.timmevandermeer.carglass.LocationActivity.java

/**
 * Load the map asynchronously and populate the ImageView when it's loaded.
 *//*from w ww  .  ja va 2  s .co m*/
private void loadMap(double latitude, double longitude, int zoom) {
    String url = makeStaticMapsUrl(52.001783, 4.368871, 10);
    new AsyncTask<String, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(String... urls) {
            try {
                HttpResponse response = new DefaultHttpClient().execute(new HttpGet(urls[0]));
                InputStream is = response.getEntity().getContent();
                return BitmapFactory.decodeStream(is);
            } catch (Exception e) {
                Log.e(TAG, "Failed to load image", e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                mMapView.setImageBitmap(bitmap);
            }
        }
    }.execute(url);
}

From source file:com.azcltd.android.test.kolesov.DrawableManager.java

private Drawable getAsBitmap(String urlString) {
    try {/*www  .ja  v a2 s  .  c  o  m*/
        InputStream is1 = (InputStream) new URL(urlString).getContent();
        Bitmap d = BitmapFactory.decodeStream(is1);
        is1.close();
        Drawable drawable = new BitmapDrawable(d);
        if (d != null)
            drawableMap.put(urlString, drawable);
        return drawable;
    } catch (Exception e1) {
        int i = 1;
    }
    return null;
}

From source file:com.atwelm.aezwidget.responses.interfaces.AEZCell.java

/**
 * Synchronously gets the icon bitmap, if available. If it has not already been fetched, it may take some time to fetch.
 * @return/*from ww w .  j  av  a  2 s  . co m*/
 */
public final Bitmap getIconBitmap() {
    String iconUrl = getIconUrl();

    if (mIconBitmap == null && iconUrl != null) {

        Log.d(LOG_TAG, "getIconBitmap at url=\"" + iconUrl + "\"");

        try {
            ResponseEntity<Resource> responseEntity = getRestTemplate().getForEntity(iconUrl, Resource.class);
            BufferedInputStream bis = new BufferedInputStream(responseEntity.getBody().getInputStream());

            mIconBitmap = BitmapFactory.decodeStream(bis);
            return mIconBitmap;
        } catch (Exception e) {
            Log.e(LOG_TAG, e.toString());
            e.printStackTrace();
            mIconBitmap = null;
        }
    }
    return mIconBitmap;
}

From source file:www.image.ImageManager.java

private Bitmap lookupFile(String url) {
    String hashedUrl = getMd5(url);

    //?/* w w w. java2s.  co  m*/
    FileInputStream fis = null;
    try {
        fis = mContext.openFileInput(hashedUrl);

        return BitmapFactory.decodeStream(fis);

    } catch (FileNotFoundException e) {
        return null;
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                // Ignore.
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
    }
}

From source file:com.othermedia.asyncimage.AsyncImageDownloader.java

@Override
public void run() {
    if (parentImageCache == null)
        return;//  w  ww . j  a va  2 s  .  co m

    // The downloader runs until the queue is empty or the cache is disconnected
    while (parentImageCache != null && parentImageCache.downloadQueue.size() > 0) {

        AsyncImageTask currentTask = parentImageCache.downloadQueue.remove(0); // Pop first task in (FIFO)

        try {

            // -- Check and retrieve file cache
            String hashedPath = null;
            try {
                if (parentImageCache.isFileCacheEnabled()) {
                    hashedPath = parentImageCache.hashString(currentTask.getImageURL()) + ".png";
                    if (parentImageCache.hasInFileCache(hashedPath)) {
                        parentImageCache.fileCacheRetrieve(hashedPath, currentTask.getImageURL());
                    }
                }
            } catch (Exception e) {
                Log.e(DebugTag, "Exception on retrieving from file cache: " + e + ": " + e.getMessage());
            }

            // - Check cache, if the image got retrieved by an earlier request or from file cache
            if (parentImageCache.hasCached(currentTask.getImageURL())) {
                parentImageCache.updateTargetFromHandler(currentTask.getTargetImageView(),
                        currentTask.getImageURL());
            } else {
                // ...Else download image:

                int tries = 3; // Allowed download Tries

                while (tries > 0) {
                    tries--; // In case of a short network drop or other random connection error.

                    try {

                        // -- Create HTTP Request
                        URL requestUrl = new URL(currentTask.getImageURL());
                        HttpGet httpRequest = new HttpGet(requestUrl.toURI());
                        HttpClient httpClient = new DefaultHttpClient();
                        HttpResponse httpResponse = (HttpResponse) httpClient.execute(httpRequest);

                        // -- Process Bitmap Download
                        BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(httpResponse.getEntity());
                        InputStream inputStream = bufferedEntity.getContent();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        BitmapDrawable drawable = new BitmapDrawable(bitmap);
                        parentImageCache.cacheImage(currentTask.getImageURL(), drawable); // - cache downloaded bitmap, then update ImageView:
                        parentImageCache.updateTargetFromHandler(currentTask.getTargetImageView(),
                                currentTask.getImageURL());

                        tries = 0; // Release tries.
                        inputStream.close();

                        // -- Cache Drawable as file, if enabled
                        if (parentImageCache.isFileCacheEnabled()) {
                            try {
                                if (hashedPath != null) {
                                    File outputFile = new File(parentImageCache.getCacheDir(), hashedPath);
                                    FileOutputStream outputStream = new FileOutputStream(outputFile);
                                    bitmap.compress(Bitmap.CompressFormat.PNG, 90, outputStream);
                                }
                            } catch (Exception e) {
                                Log.e(DebugTag,
                                        "Exception on file caching process: " + e + ": " + e.getMessage());
                            }
                        } // -- End file caching.

                    } catch (Exception e) {
                        Log.e(DebugTag, "Exception on download process: " + e + ": " + e.getMessage());
                        try {
                            Thread.sleep(250);
                        } catch (InterruptedException ei) {
                        }
                    }
                }
            }

        } catch (Exception e) {
            Log.e(DebugTag, "Exception on current AsyncImageTask: " + e + ": " + e.getMessage());
        }

    }

    parentImageCache.downloaderFinished(); // Release thread reference from cache

}