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:semanticweb.hws14.movapp.activities.MovieDetail.java

private void setData(final MovieDet movie) {
    Thread picThread = new Thread(new Runnable() {
        public void run() {
            try {
                ImageView img = (ImageView) findViewById(R.id.imageViewMovie);
                URL url = new URL(movie.getPoster());
                HttpGet httpRequest;//  w  w w .j a va2 s .  c  om

                httpRequest = new HttpGet(url.toURI());

                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(httpRequest);

                HttpEntity entity = response.getEntity();
                BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
                InputStream input = b_entity.getContent();

                Bitmap bitmap = BitmapFactory.decodeStream(input);

                img.setImageBitmap(bitmap);

            } catch (Exception ex) {
                Log.d("MovieDetail Picture Error ", ex.toString());
            }
        }
    });
    picThread.start();

    if (!"".equals(movie.getTitle())) {
        TextView movieTitle = (TextView) findViewById(R.id.tvMovieTitle);
        movieTitle.setText(movie.getTitle());
        movieTitle.setVisibility(View.VISIBLE);
    }

    if (!"".equals(movie.getPlot())) {
        TextView moviePlot = (TextView) findViewById(R.id.tvPlot);
        moviePlot.setText(movie.getPlot());
        moviePlot.setVisibility(View.VISIBLE);
    }

    TextView ageRestriction = (TextView) findViewById(R.id.tvAgeRestriction);
    TextView arHc = (TextView) findViewById(R.id.tvAgeRestrictionHC);
    String aR = String.valueOf(movie.getRated());

    //Decode the ageRestriction
    if (!aR.equals("")) {
        ageRestriction.setVisibility(View.VISIBLE);
        arHc.setVisibility(View.VISIBLE);
        if (aR.equals("X")) {
            ageRestriction.setText("18+");
        } else if (aR.equals("R")) {
            ageRestriction.setText("16+");
        } else if (aR.equals("M")) {
            ageRestriction.setText("12+");
        } else if (aR.equals("G")) {
            ageRestriction.setText("6+");
        } else {
            ageRestriction.setVisibility(View.GONE);
            arHc.setVisibility(View.GONE);
        }
    }

    TextView ratingCount = (TextView) findViewById(R.id.tvMovieRatingCount);
    TextView ratingCountHc = (TextView) findViewById(R.id.tvMovieRatingCountHC);
    String ratingCountText = movie.getVoteCount();
    ratingCount.setText(ratingCountText);
    manageEmptyTextfields(ratingCountHc, ratingCount, ratingCountText, false);

    if (!"".equals(movie.getImdbRating())) {
        TextView movieRating = (TextView) findViewById(R.id.tvMovieRating);
        if (movie.getImdbRating().equals("0 No Rating")) {
            movieRating.setText("No Rating");
        } else if (movie.getImdbRating().equals("0 No Data")) {
            movieRating.setText("");
        } else {
            movieRating.setText(movie.getImdbRating() + "/10");
        }
        movieRating.setVisibility(View.VISIBLE);
        findViewById(R.id.tvMovieRatingHC).setVisibility(View.VISIBLE);
    }

    TextView metaScore = (TextView) findViewById(R.id.tvMetaScore);
    TextView metaScoreHc = (TextView) findViewById(R.id.tvMetaScoreHC);
    String metaSoreText = String.valueOf(movie.getMetaScore());
    metaScore.setText(metaSoreText + "/100");
    manageEmptyTextfields(metaScoreHc, metaScore, metaSoreText, false);

    TextView tvGenreHc = (TextView) findViewById(R.id.tvGenreHC);
    TextView genre = (TextView) findViewById(R.id.tvGenre);
    String genreText = String.valueOf(movie.createTvOutOfList(movie.getGenres()));
    genre.setText(genreText);
    manageEmptyTextfields(tvGenreHc, genre, genreText, true);

    TextView releaseYear = (TextView) findViewById(R.id.tvReleaseYear);
    TextView releaseYearHc = (TextView) findViewById(R.id.tvReleaseYearHC);
    String releaseYearText = String.valueOf(movie.getReleaseYear());
    releaseYear.setText(releaseYearText);
    manageEmptyTextfields(releaseYearHc, releaseYear, releaseYearText, true);

    TextView runtime = (TextView) findViewById(R.id.tvRuntime);
    TextView runTimeHc = (TextView) findViewById(R.id.tvRuntimeHC);
    String runtimeText = "";
    try {
        runtimeText = runtimeComputation(Float.parseFloat(movie.getRuntime()));
    } catch (Exception e) {
        runtimeText = movie.getRuntime();
    }
    runtime.setText(runtimeText);
    manageEmptyTextfields(runTimeHc, runtime, runtimeText, true);

    TextView budget = (TextView) findViewById(R.id.tvBudget);
    TextView budgetHc = (TextView) findViewById(R.id.tvBudgetHC);
    String budgetText = movie.getBudget();
    //Decode the budget
    if (budgetText.contains("E")) {
        BigDecimal myNumber = new BigDecimal(budgetText);
        long budgetLong = myNumber.longValue();
        NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.US);
        budgetText = formatter.format(budgetLong);
        budgetText = String.valueOf(budgetText);
        budgetText = budgetComputation(budgetText);
        budget.setText(budgetText);
        manageEmptyTextfields(budgetHc, budget, budgetText, true);
    }

    TextView awards = (TextView) findViewById(R.id.tvAwards);
    TextView awardsHc = (TextView) findViewById(R.id.tvAwardsHC);
    String awardsText = movie.getAwards();
    awards.setText(awardsText);
    manageEmptyTextfields(awardsHc, awards, awardsText, true);

    TextView tvDirHc = (TextView) findViewById(R.id.tvDirectorsHC);
    TextView directors = (TextView) findViewById(R.id.tvDirectors);
    String directorText = String.valueOf(movie.createTvOutOfList(movie.getDirectors()));
    directors.setText(directorText);
    manageEmptyTextfields(tvDirHc, directors, directorText, true);

    TextView tvWriterHc = (TextView) findViewById(R.id.tvWritersHC);
    TextView writers = (TextView) findViewById(R.id.tvWriters);
    String writerText = String.valueOf(movie.createTvOutOfList(movie.getWriters()));
    writers.setText(writerText);
    manageEmptyTextfields(tvWriterHc, writers, writerText, true);

    TextView tvActorsHc = (TextView) findViewById(R.id.tvActorsHC);
    TextView actors = (TextView) findViewById(R.id.tvActors);
    String actorText = String.valueOf(movie.createTvOutOfList(movie.getActors()));
    actors.setText(actorText);
    manageEmptyTextfields(tvActorsHc, actors, actorText, true);
    colorIt(actors);

    if (movie.getActors().size() > 0) {
        btnActorList.setVisibility(View.VISIBLE);
    }

    btnRandomRelatedMovies.setVisibility(View.VISIBLE);
    btnRelatedMovies.setVisibility(View.VISIBLE);

    TextView tvRolesHc = (TextView) findViewById(R.id.tvRolesHC);
    TextView roles = (TextView) findViewById(R.id.tvRoles);
    ArrayList<String> roleList = movie.getRoles();

    if (roleList.size() > 0) {
        roles.setVisibility(View.VISIBLE);
        tvRolesHc.setVisibility(View.VISIBLE);
        roles.setText(String.valueOf(movie.createTvOutOfList(roleList)));
    }

    TextView wikiAbstract = (TextView) findViewById(R.id.tvWikiAbstract);
    wikiAbstract.setText(movie.getWikiAbstract());
    if (!"".equals(movie.getImdbId())) {
        btnImdbPage.setVisibility(View.VISIBLE);
    }
    if (!"".equals(movie.getWikiAbstract())) {
        btnSpoiler.setVisibility(View.VISIBLE);
    }
    try {
        picThread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    setProgressBarIndeterminateVisibility(false);
}

From source file:net.sourcewalker.garanbot.api.ItemService.java

public Bitmap getPicture(int id) throws ClientException {
    try {//from www .  jav  a2 s  . c  om
        HttpResponse response = client.get("/item/" + id + "/picture");
        int statusCode = response.getStatusLine().getStatusCode();
        switch (statusCode) {
        case HttpStatus.SC_OK:
            Base64InputStream stream = new Base64InputStream(response.getEntity().getContent(), Base64.DEFAULT);
            Bitmap result = BitmapFactory.decodeStream(stream);
            if (result == null) {
                throw new ClientException("Picture could not be decoded!");
            }
            return result;
        case HttpStatus.SC_NOT_FOUND:
            return null;
        default:
            throw new ClientException("Got HTTP error: " + response.getStatusLine().toString());
        }
    } catch (IOException e) {
        throw new ClientException("IO error: " + e.getMessage(), e);
    }
}

From source file:com.andrewshu.android.reddit.threads.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.//from w  w  w. ja  va2  s .com
 *
 * 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) {
    InputStream is = null;
    BufferedInputStream bis = null;
    Bitmap 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.");
        }
    }
    return bmp;
}

From source file:ca.psiphon.ploggy.Robohash.java

private static Bitmap loadAssetToBitmap(AssetManager assetManager, String assetName) throws IOException {
    InputStream inputStream = null;
    try {//w w w .j  a  va2 s.c o  m
        inputStream = assetManager.open(new File(ASSETS_SUBDIRECTORY, assetName).getPath());
        return BitmapFactory.decodeStream(inputStream);
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
}

From source file:edu.rowan.app.carousel.CarouselFetch.java

/** TODO: delete this, it's not used
 * Download image/* ww w  . j ava2s  . c  o  m*/
 */
static Bitmap downloadBitmap(String url) {
    final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
    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();
                final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                return bitmap;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                entity.consumeContent();
            }
        }
    } catch (Exception e) {
        // Could provide a more explicit error message for IOException or IllegalStateException
        getRequest.abort();
        Log.w("ImageDownloader", "Error while retrieving bitmap from " + url);
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}

From source file:com.cleverua.test.thumbs.ImageDownloader.java

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

    try {//from w ww  . j ava  2s.c o  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);
    }
    return null;
}

From source file:com.nttec.everychan.http.recaptcha.Recaptcha2fallback.java

@Override
public void handle(final Activity activity, final CancellableTask task, final Callback callback) {
    try {/*from w w w  .j av a 2 s . c  o m*/
        final HttpClient httpClient = ((HttpChanModule) MainApplication.getInstance().getChanModule(chanName))
                .getHttpClient();
        final String usingURL = scheme + RECAPTCHA_FALLBACK_URL + publicKey
                + (sToken != null && sToken.length() > 0 ? ("&stoken=" + sToken) : "");
        String refererURL = baseUrl != null && baseUrl.length() > 0 ? baseUrl : usingURL;
        Header[] customHeaders = new Header[] { new BasicHeader(HttpHeaders.REFERER, refererURL) };
        String htmlChallenge;
        if (lastChallenge != null && lastChallenge.getLeft().equals(usingURL)) {
            htmlChallenge = lastChallenge.getRight();
        } else {
            htmlChallenge = HttpStreamer.getInstance().getStringFromUrl(usingURL,
                    HttpRequestModel.builder().setGET().setCustomHeaders(customHeaders).build(), httpClient,
                    null, task, false);
        }
        lastChallenge = null;

        Matcher challengeMatcher = Pattern.compile("name=\"c\" value=\"([\\w-]+)").matcher(htmlChallenge);
        if (challengeMatcher.find()) {
            final String challenge = challengeMatcher.group(1);
            HttpResponseModel responseModel = HttpStreamer.getInstance().getFromUrl(
                    scheme + RECAPTCHA_IMAGE_URL + challenge + "&k=" + publicKey,
                    HttpRequestModel.builder().setGET().setCustomHeaders(customHeaders).build(), httpClient,
                    null, task);
            try {
                InputStream imageStream = responseModel.stream;
                final Bitmap challengeBitmap = BitmapFactory.decodeStream(imageStream);

                final String message;
                Matcher messageMatcher = Pattern.compile("imageselect-message(?:.*?)>(.*?)</div>")
                        .matcher(htmlChallenge);
                if (messageMatcher.find())
                    message = RegexUtils.removeHtmlTags(messageMatcher.group(1));
                else
                    message = null;

                final Bitmap candidateBitmap;
                Matcher candidateMatcher = Pattern
                        .compile("fbc-imageselect-candidates(?:.*?)src=\"data:image/(?:.*?);base64,([^\"]*)\"")
                        .matcher(htmlChallenge);
                if (candidateMatcher.find()) {
                    Bitmap bmp = null;
                    try {
                        byte[] imgData = Base64.decode(candidateMatcher.group(1), Base64.DEFAULT);
                        bmp = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
                    } catch (Exception e) {
                    }
                    candidateBitmap = bmp;
                } else
                    candidateBitmap = null;

                activity.runOnUiThread(new Runnable() {
                    final int maxX = 3;
                    final int maxY = 3;
                    final boolean[] isSelected = new boolean[maxX * maxY];

                    @SuppressLint("InlinedApi")
                    @Override
                    public void run() {
                        LinearLayout rootLayout = new LinearLayout(activity);
                        rootLayout.setOrientation(LinearLayout.VERTICAL);

                        if (candidateBitmap != null) {
                            ImageView candidateView = new ImageView(activity);
                            candidateView.setImageBitmap(candidateBitmap);
                            int picSize = (int) (activity.getResources().getDisplayMetrics().density * 50
                                    + 0.5f);
                            candidateView.setLayoutParams(new LinearLayout.LayoutParams(picSize, picSize));
                            candidateView.setScaleType(ImageView.ScaleType.FIT_XY);
                            rootLayout.addView(candidateView);
                        }

                        if (message != null) {
                            TextView textView = new TextView(activity);
                            textView.setText(message);
                            CompatibilityUtils.setTextAppearance(textView, android.R.style.TextAppearance);
                            textView.setLayoutParams(
                                    new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                            LinearLayout.LayoutParams.WRAP_CONTENT));
                            rootLayout.addView(textView);
                        }

                        FrameLayout frame = new FrameLayout(activity);
                        frame.setLayoutParams(
                                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT));

                        final ImageView imageView = new ImageView(activity);
                        imageView.setLayoutParams(new FrameLayout.LayoutParams(
                                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
                        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        imageView.setImageBitmap(challengeBitmap);
                        frame.addView(imageView);

                        final LinearLayout selector = new LinearLayout(activity);
                        selector.setLayoutParams(new FrameLayout.LayoutParams(
                                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
                        AppearanceUtils.callWhenLoaded(imageView, new Runnable() {
                            @Override
                            public void run() {
                                selector.setLayoutParams(new FrameLayout.LayoutParams(imageView.getWidth(),
                                        imageView.getHeight()));
                            }
                        });
                        selector.setOrientation(LinearLayout.VERTICAL);
                        selector.setWeightSum(maxY);
                        for (int y = 0; y < maxY; ++y) {
                            LinearLayout subSelector = new LinearLayout(activity);
                            subSelector.setLayoutParams(new LinearLayout.LayoutParams(
                                    LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f));
                            subSelector.setOrientation(LinearLayout.HORIZONTAL);
                            subSelector.setWeightSum(maxX);
                            for (int x = 0; x < maxX; ++x) {
                                FrameLayout switcher = new FrameLayout(activity);
                                switcher.setLayoutParams(new LinearLayout.LayoutParams(0,
                                        LinearLayout.LayoutParams.MATCH_PARENT, 1f));
                                switcher.setTag(new int[] { x, y });
                                switcher.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        int[] coord = (int[]) v.getTag();
                                        int index = coord[1] * maxX + coord[0];
                                        isSelected[index] = !isSelected[index];
                                        v.setBackgroundColor(isSelected[index] ? Color.argb(128, 0, 255, 0)
                                                : Color.TRANSPARENT);
                                    }
                                });
                                subSelector.addView(switcher);
                            }
                            selector.addView(subSelector);
                        }

                        frame.addView(selector);
                        rootLayout.addView(frame);

                        Button checkButton = new Button(activity);
                        checkButton.setLayoutParams(
                                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT));
                        checkButton.setText(android.R.string.ok);
                        rootLayout.addView(checkButton);

                        ScrollView dlgView = new ScrollView(activity);
                        dlgView.addView(rootLayout);

                        final Dialog dialog = new Dialog(activity);
                        dialog.setTitle("Recaptcha");
                        dialog.setContentView(dlgView);
                        dialog.setCanceledOnTouchOutside(false);
                        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                if (!task.isCancelled()) {
                                    callback.onError("Cancelled");
                                }
                            }
                        });
                        dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT);
                        dialog.show();

                        checkButton.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                if (task.isCancelled())
                                    return;
                                Async.runAsync(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                                            pairs.add(new BasicNameValuePair("c", challenge));
                                            for (int i = 0; i < isSelected.length; ++i)
                                                if (isSelected[i])
                                                    pairs.add(new BasicNameValuePair("response",
                                                            Integer.toString(i)));

                                            HttpRequestModel request = HttpRequestModel.builder()
                                                    .setPOST(new UrlEncodedFormEntity(pairs, "UTF-8"))
                                                    .setCustomHeaders(new Header[] {
                                                            new BasicHeader(HttpHeaders.REFERER, usingURL) })
                                                    .build();
                                            String response = HttpStreamer.getInstance().getStringFromUrl(
                                                    usingURL, request, httpClient, null, task, false);
                                            String hash = "";
                                            Matcher matcher = Pattern.compile(
                                                    "fbc-verification-token(?:.*?)<textarea[^>]*>([^<]*)<",
                                                    Pattern.DOTALL).matcher(response);
                                            if (matcher.find())
                                                hash = matcher.group(1);

                                            if (hash.length() > 0) {
                                                Recaptcha2solved.push(publicKey, hash);
                                                activity.runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        callback.onSuccess();
                                                    }
                                                });
                                            } else {
                                                lastChallenge = Pair.of(usingURL, response);
                                                throw new RecaptchaException(
                                                        "incorrect answer (hash is empty)");
                                            }
                                        } catch (final Exception e) {
                                            Logger.e(TAG, e);
                                            if (task.isCancelled())
                                                return;
                                            handle(activity, task, callback);
                                        }
                                    }
                                });
                            }
                        });
                    }
                });
            } finally {
                responseModel.release();
            }
        } else
            throw new Exception("can't parse recaptcha challenge answer");
    } catch (final Exception e) {
        Logger.e(TAG, e);
        if (!task.isCancelled()) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    callback.onError(e.getMessage() != null ? e.getMessage() : e.toString());
                }
            });
        }
    }
}

From source file:com.lge.osclibrary.OSCCommandsExecute.java

/**
 * Read response data and convert to particular data type depending on the command
 *
 * @param inputStream response stream data from server
 * @return response data/*from w ww .j av a  2 s . c  om*/
 */
@Override
protected Object parseResponse(InputStream inputStream) {
    Log.d(TAG, "----------------------------------- Child parse response ===== " + commandType);
    if (commandType == CommandType.IMAGE) {
        try {
            if (mParameters.has(OSCParameterNameMapper.MAXSIZE)) {
                //For thumbnail, return  bitmap image
                return BitmapFactory.decodeStream(inputStream);
            } else {
                //For full image, save image in local storage
                return saveBitmap(mParameters.getString(OSCParameterNameMapper.FILEURL),
                        BitmapFactory.decodeStream(inputStream));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } else if (commandType == CommandType.VIDEO) {
        try {
            if (mParameters.has(OSCParameterNameMapper.MAXSIZE)) {
                //For thumbnail, return bitmap image
                return BitmapFactory.decodeStream(inputStream);
            } else {
                //For full video, save video in local storage
                return saveVideo(mParameters.getString(OSCParameterNameMapper.FILEURL), inputStream);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } else if (commandType == CommandType.PREVIEW) {
        //For preview(getLivePreview commands), return bitmap image
        return BitmapFactory.decodeStream(inputStream);
    }

    return super.parseResponse(inputStream);
}

From source file:com.socialize.util.ImageUtils.java

public static Bitmap getBitmapFromURL(String src) {
    Bitmap myBitmap = null;//w ww  . j  a v  a 2s. co m
    HttpURLConnection connection = null;

    try {
        URL url = new URL(src);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        myBitmap = BitmapFactory.decodeStream(input);
    } catch (IOException e) {
        e.printStackTrace();
        myBitmap = null;
    } finally {
        try {
            connection.disconnect();
        } catch (Exception ignored) {
        }
    }

    return myBitmap;
}

From source file:com.luyaozhou.recognizethisforglass.ViewFinder.java

private void processPictureWhenReady(final String picturePath) {
    final File pictureFile = new File(picturePath);
    //Map<String, String > result = new HashMap<String,String>();

    if (pictureFile.exists()) {
        // The picture is ready; process it.
        Bitmap imageBitmap = null;// w  ww .  j a  v  a2s. c o  m
        try {
            //               Bundle extras = data.getExtras();
            //               imageBitmap = (Bitmap) extras.get("data");
            FileInputStream fis = new FileInputStream(picturePath); //get the bitmap from file
            imageBitmap = (Bitmap) BitmapFactory.decodeStream(fis);

            if (imageBitmap != null) {
                Bitmap lScaledBitmap = Bitmap.createScaledBitmap(imageBitmap, 1600, 1200, false);
                if (lScaledBitmap != null) {
                    imageBitmap.recycle();
                    imageBitmap = null;

                    ByteArrayOutputStream lImageBytes = new ByteArrayOutputStream();
                    lScaledBitmap.compress(Bitmap.CompressFormat.JPEG, 30, lImageBytes);
                    lScaledBitmap.recycle();
                    lScaledBitmap = null;

                    byte[] lImageByteArray = lImageBytes.toByteArray();

                    HashMap<String, String> lValuePairs = new HashMap<String, String>();
                    lValuePairs.put("base64Image", Base64.encodeToString(lImageByteArray, Base64.DEFAULT));
                    lValuePairs.put("compressionLevel", "30");
                    lValuePairs.put("documentIdentifier", "DRIVER_LICENSE_CA");
                    lValuePairs.put("documentHints", "");
                    lValuePairs.put("dataReturnLevel", "15");
                    lValuePairs.put("returnImageType", "1");
                    lValuePairs.put("rotateImage", "0");
                    lValuePairs.put("data1", "");
                    lValuePairs.put("data2", "");
                    lValuePairs.put("data3", "");
                    lValuePairs.put("data4", "");
                    lValuePairs.put("data5", "");
                    lValuePairs.put("userName", "zbroyan@miteksystems.com");
                    lValuePairs.put("password", "google1");
                    lValuePairs.put("phoneKey", "1");
                    lValuePairs.put("orgName", "MobileImagingOrg");

                    String lSoapMsg = formatSOAPMessage("InsertPhoneTransaction", lValuePairs);

                    DefaultHttpClient mHttpClient = new DefaultHttpClient();
                    //                        mHttpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.R)
                    HttpPost mHttpPost = new HttpPost();

                    mHttpPost.setHeader("User-Agent", "UCSD Team");
                    mHttpPost.setHeader("Content-typURIe", "text/xml;charset=UTF-8");
                    //mHttpPost.setURI(URI.create("https://mi1.miteksystems.com/mobileimaging/ImagingPhoneService.asmx?op=InsertPhoneTransaction"));
                    mHttpPost.setURI(
                            URI.create("https://mi1.miteksystems.com/mobileimaging/ImagingPhoneService.asmx"));

                    StringEntity se = new StringEntity(lSoapMsg, HTTP.UTF_8);
                    se.setContentType("text/xml; charset=UTF-8");
                    mHttpPost.setEntity(se);
                    HttpResponse mResponse = mHttpClient.execute(mHttpPost, new BasicHttpContext());

                    String responseString = new BasicResponseHandler().handleResponse(mResponse);
                    parseXML(responseString);

                    //Todo: this is test code. Need to be implemented
                    //result = parseXML(testStr);
                    Log.i("test", "test:" + " " + responseString);
                    Log.i("test", "test: " + " " + map.size());

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // this part will be relocated in order to let the the server process picture
        if (map.size() == 0) {
            Intent display = new Intent(getApplicationContext(), DisplayInfoFailed.class);
            display.putExtra("result", (java.io.Serializable) iQAMsg);
            startActivity(display);
        } else {
            Intent display = new Intent(getApplicationContext(), DisplayInfo.class);
            display.putExtra("result", (java.io.Serializable) map);
            startActivity(display);

        }
    } else {
        // The file does not exist yet. Before starting the file observer, you
        // can update your UI to let the user know that the application is
        // waiting for the picture (for example, by displaying the thumbnail
        // image and a progress indicator).

        final File parentDirectory = pictureFile.getParentFile();
        FileObserver observer = new FileObserver(parentDirectory.getPath(),
                FileObserver.CLOSE_WRITE | FileObserver.MOVED_TO) {
            // Protect against additional pending events after CLOSE_WRITE
            // or MOVED_TO is handled.
            private boolean isFileWritten;

            @Override
            public void onEvent(int event, final String path) {
                if (!isFileWritten) {
                    // For safety, make sure that the file that was created in
                    // the directory is actually the one that we're expecting.
                    File affectedFile = new File(parentDirectory, path);
                    isFileWritten = affectedFile.equals(pictureFile);

                    if (isFileWritten) {
                        stopWatching();
                        // Now that the file is ready, recursively call
                        // processPictureWhenReady again (on the UI thread).
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                new LongOperation().execute(picturePath);
                            }
                        });
                    }
                }
            }
        };
        observer.startWatching();

    }

}