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.image.oom.ImageUtil.java

Bitmap downloadBitmap(String url) {
    final int IO_BUFFER_SIZE = 4 * 1024;
    try {//from  w  w  w .j  av  a2 s  .com
        final Bitmap bit = getBitMap(url, 480, 480);
        if (bit != null) {
            return bit;
        }
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    HttpClient client = new DefaultHttpClient();
    final HttpGet getRequest = new HttpGet(url);

    try {
        HttpResponse response = client.execute(getRequest);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
            return null;
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {
                inputStream = entity.getContent();
                return BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                entity.consumeContent();
            }
        }
    } catch (IOException e) {
        getRequest.abort();
        Log.w(LOG_TAG, "I/O error while retrieving bitmap from " + url, e);
    } catch (IllegalStateException e) {
        getRequest.abort();
        Log.w(LOG_TAG, "Incorrect URL: " + url);
    } catch (Exception e) {
        getRequest.abort();
        Log.w(LOG_TAG, "Error while retrieving bitmap from " + url, e);
    } finally {
        if ((client instanceof AndroidHttpClient)) {
            ((AndroidHttpClient) client).close();
        }
    }
    return null;
}

From source file:com.sparkhunter.activities.FbfriendsActivity.java

public Bitmap getBitmap(String url) {
    AndroidHttpClient httpclient = null;
    Bitmap bm = null;/*  w w  w. j  a  v  a2 s  .com*/
    try {
        URL aURL = new URL(url);
        URLConnection conn = aURL.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        bm = BitmapFactory.decodeStream(new FlushedInputStream(is));
        bis.close();
        is.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (httpclient != null) {
            httpclient.close();
        }
    }
    return bm;
}

From source file:com.siahmsoft.soundwaper.net.SoundcloudApi.java

public Bitmap retrieveBitmap(URL photoUrl) {
    Bitmap bitmap = null;//  w  w  w. j a v  a2  s  . c  o m

    if (BitmapCache.isInCache(photoUrl.toString())) {
        bitmap = BitmapCache.get(photoUrl.toString());
    } else {
        int retries = 0;
        do {
            if (retries > 0) {
                Log.e(TAG, "Couldn't retrieve Image. Retrying for " + retries + " time");
            }
            try {
                HttpResponse response = netMgr.getHTTPResponse(photoUrl);
                Object input = response.getEntity().getContent();
                InputStream inputStream = (InputStream) input;
                bitmap = BitmapFactory.decodeStream(inputStream);
                BitmapCache.put(photoUrl.toString(), bitmap);
            } catch (IllegalArgumentException e) {
                Log.e(TAG, "Could not retireve bitmap wth null URL", e);
            } catch (IOException e) {
                Log.e(TAG, "Could not retrieve bitmap from resulting httpResponse", e);
            }
            retries++;
        } while (bitmap == null && retries < 3);
    }

    return bitmap;
}

From source file:com.binroot.fatpita.BitmapManager.java

/**
 * http://ballardhack.wordpress.com/2010/04/10/loading-images-over-http-on-a-separate-thread-on-android/
 * Convenience method to retrieve a bitmap image from
 * a URL over the network. The built-in methods do
 * not seem to work, as they return a FileNotFound
 * exception./*w ww .  j  av a2  s .  c o m*/
 *
 * Note that this does not perform any threading --
 * it blocks the call while retrieving the data.
 *
 * @param url The URL to read the bitmap from.
 * @return A Bitmap image or null if an error occurs.
 */
public Bitmap readBitmapFromNetwork(String url, boolean saveToHistory) {

    InputStream is = null;
    BufferedInputStream bis = null;
    Bitmap bmp = null;

    while (bmp == null) {
        try {
            is = fetch(url);
            bis = new BufferedInputStream(is);
            bmp = BitmapFactory.decodeStream(bis);
        } catch (MalformedURLException e) {
            Log.e(TAG, "Bad ad URL", e);
        } catch (IOException e) {
            Log.e(TAG, "Could not get remote ad image", e);
        } finally {
            try {
                if (is != null)
                    is.close();
                if (bis != null)
                    bis.close();
            } catch (IOException e) {
                Log.w(TAG, "Error closing stream.");
            }
        }

        if (bmp == null) {
            url = URLFinder.randomURL();
        } else if (bmp.getWidth() > 1000 || bmp.getHeight() > 1000) {
            bmp = null;
            url = URLFinder.randomURL();
        }
    }

    appState.setURL(url);
    if (saveToHistory) {
        appState.getHistory().add(url);
        appState.setBackCursor(appState.getHistory().size() - 1);
    }

    if (!appState.getFavList().contains(appState.getURL())) {
        favButton.setBackgroundResource(android.R.drawable.btn_star);
    } else {
        favButton.setBackgroundResource(android.R.drawable.btn_star_big_on);
    }

    return bmp;
}

From source file:com.liato.bankdroid.banking.banks.Nordea.Nordea.java

@Override
public Urllib login() throws LoginException, BankException {
    try {//from   w  w w .j a  va 2s .c o  m
        LoginPackage lp = preLogin();
        String response = urlopen.open(lp.getLoginTarget(), lp.getPostData());
        if (response.contains("felaktiga uppgifter")) {
            throw new LoginException(res.getText(R.string.invalid_username_password).toString());
        } else if (response.contains("nloggningar med ditt personnummer idag")) {
            Matcher matcher = reCSRF.matcher(response);
            if (!matcher.find()) {
                throw new BankException(res.getText(R.string.unable_to_find).toString() + " CSRF token.");
            }
            String csrftoken = matcher.group(1);
            Iterator<NameValuePair> it = lp.getPostData().iterator();
            while (it.hasNext()) {
                NameValuePair nv = it.next();
                if (nv.getName().equals("_csrf_token")) {
                    it.remove();
                    break;
                }
            }
            lp.getPostData().add(new BasicNameValuePair("_csrf_token", csrftoken));
            //Too many logins, we need to solve a captcha.
            Bitmap bm = BitmapFactory.decodeStream(
                    urlopen.openStream("https://mobil.nordea.se/banking-nordea/nordea-c3/captcha.png"));
            String captcha = CaptchaBreaker.iMustBreakYou(bm);
            bm.recycle();
            bm = null;
            lp.getPostData().add(new BasicNameValuePair("captcha", captcha));
            response = urlopen.open(lp.getLoginTarget(), lp.getPostData());
            if (response.contains("felaktiga uppgifter")) {
                throw new LoginException(res.getText(R.string.invalid_username_password).toString());
            }
        }

    } catch (ClientProtocolException e) {
        throw new BankException(e.getMessage());
    } catch (IOException e) {
        throw new BankException(e.getMessage());
    }
    return urlopen;
}

From source file:com.scoreloop.client.android.ui.util.ImageDownloader.java

Bitmap downloadBitmapHttp(String url) {
    // Requires API Level 8: AndroidHttpClient is not allowed to be used from the main thread
    //final HttpClient client = (mode == Mode.NO_ASYNC_TASK) ? new DefaultHttpClient() :
    //    AndroidHttpClient.newInstance("Android");
    final HttpClient client = new DefaultHttpClient();
    final HttpGet getRequest = new HttpGet(url);

    try {//from   www.j av a  2 s.  c o  m
        HttpResponse response = client.execute(getRequest);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            return null;
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {
                inputStream = entity.getContent();
                // return BitmapFactory.decodeStream(inputStream);
                // Bug on slow connections, fixed in future release.
                return BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                entity.consumeContent();
            }
        }
    } catch (IOException e) {
        getRequest.abort();
    } catch (IllegalStateException e) {
        getRequest.abort();
    } catch (Exception e) {
        getRequest.abort();
    } finally {
        // Requires API Level 8
        //if ((client instanceof AndroidHttpClient)) {
        //    ((AndroidHttpClient) client).close();
        //}
    }
    return null;
}

From source file:com.ankit.touchreview.FinalActivity.java

public void setThemeImage(final String themeimage) {
    new Thread() {
        public void run() {
            try {
                InputStream is = (InputStream) new URL(themeimage).getContent();
                Bitmap bmImg = BitmapFactory.decodeStream(is);
                @SuppressWarnings("deprecation")
                final BitmapDrawable background = new BitmapDrawable(bmImg);
                runOnUiThread(new Runnable() {
                    @SuppressWarnings("deprecation")
                    @Override/*from ww w.  j a  v  a2  s. c o  m*/
                    public void run() {
                        LinearLayout1.setBackgroundDrawable(background);
                    }
                });
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }.start();
}

From source file:at.zone.madeleine.slideshow.ImageDownloader.java

Bitmap downloadBitmap(String url) {
    // AndroidHttpClient is not allowed to be used from the main thread
    final HttpClient client = AndroidHttpClient.newInstance("Android");
    final HttpGet getRequest = new HttpGet(url);

    boolean networkError = false;

    try {//from   w ww . ja  va 2s  .c  om
        HttpResponse response = client.execute(getRequest);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            networkError = true;
            return null;
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {
                inputStream = entity.getContent();
                // return BitmapFactory.decodeStream(inputStream);
                // Bug on slow connections, fixed in future release.
                return BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                entity.consumeContent();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        getRequest.abort();
        networkError = true;
    } catch (IllegalStateException e) {
        e.printStackTrace();
        getRequest.abort();
        networkError = true;
    } catch (Exception e) {
        e.printStackTrace();
        getRequest.abort();
        networkError = true;
    } finally {
        if ((client instanceof AndroidHttpClient)) {
            ((AndroidHttpClient) client).close();
        }
        if (networkError) {
            // inform the activity that we have network error(s)
            netwrkErrorDelegate.onNetworkError();
        }
    }
    return null;
}

From source file:com.color.droid.efficientimageloading.ImageDownloader.java

Bitmap downloadBitmap(String url) {

    // AndroidHttpClient is not allowed to be used from the main thread
    final HttpClient client = AndroidHttpClient.newInstance("Android");

    final HttpGet getRequest = new HttpGet(url);

    try {/* w  w w. j a va  2 s . co m*/
        HttpResponse response = client.execute(getRequest);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
            return null;
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {
                inputStream = entity.getContent();
                // return BitmapFactory.decodeStream(inputStream);
                // Bug on slow connections, fixed in future release.
                return BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                entity.consumeContent();
            }
        }
    } catch (IOException e) {
        getRequest.abort();
        Log.w(LOG_TAG, "I/O error while retrieving bitmap from " + url, e);
    } catch (IllegalStateException e) {
        getRequest.abort();
        Log.w(LOG_TAG, "Incorrect URL: " + url);
    } catch (Exception e) {
        getRequest.abort();
        Log.w(LOG_TAG, "Error while retrieving bitmap from " + url, e);
    } finally {
        if ((client instanceof AndroidHttpClient)) {
            ((AndroidHttpClient) client).close();
        }
    }
    return null;
}

From source file:com.aware.ui.Plugins_Manager.java

/**
* Downloads and compresses image for optimized icon caching
* @param image_url/*  w  ww  .jav a 2  s  .  co m*/
* @return
*/
public static byte[] cacheImage(String image_url, Context sContext) {
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream caInput = sContext.getResources().openRawResource(R.raw.aware);
        Certificate ca;
        try {
            ca = cf.generateCertificate(caInput);
        } finally {
            caInput.close();
        }

        KeyStore sKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream inStream = sContext.getResources().openRawResource(R.raw.awareframework);
        sKeyStore.load(inStream, "awareframework".toCharArray());
        inStream.close();

        sKeyStore.setCertificateEntry("ca", ca);

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(sKeyStore);

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);

        //Fetch image now that we recognise SSL
        URL image_path = new URL(image_url.replace("http://", "https://")); //make sure we are fetching the images over https
        HttpsURLConnection image_connection = (HttpsURLConnection) image_path.openConnection();
        image_connection.setSSLSocketFactory(context.getSocketFactory());

        InputStream in_stream = image_connection.getInputStream();
        Bitmap tmpBitmap = BitmapFactory.decodeStream(in_stream);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        tmpBitmap.compress(Bitmap.CompressFormat.PNG, 100, output);

        return output.toByteArray();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    return null;
}