Example usage for android.graphics BitmapFactory decodeFile

List of usage examples for android.graphics BitmapFactory decodeFile

Introduction

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

Prototype

public static Bitmap decodeFile(String pathName, Options opts) 

Source Link

Document

Decode a file path into a bitmap.

Usage

From source file:Main.java

private static Bitmap getMutableBitmap(String filePath) {
    return BitmapFactory.decodeFile(filePath, getMutableOption());
}

From source file:com.lightbox.android.bitmap.BitmapUtils.java

/**
 * Get the size of a bitmap from disk//w w  w  .  java  2s  .com
 * @param absoluteFileName
 */
public static BitmapSize getBitmapSizeFromFile(String absoluteFileName) {
    Options opts = new Options();
    opts.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(absoluteFileName, opts);
    return new BitmapSize(opts.outWidth, opts.outHeight);
}

From source file:Main.java

private static int getScale(String imagePath, int desiredWidth, int desiredHeight) {
    //Get image size
    BitmapFactory.Options imageInfo = new BitmapFactory.Options();
    imageInfo.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(imagePath, imageInfo);

    //Compute the scaling factor
    int scale = 1;
    int width = imageInfo.outWidth;
    int height = imageInfo.outHeight;
    //if (size < imageInfo.outHeight) size = imageInfo.outHeight;
    //while (size/(scale*2) >= ICON_SIZE) {
    while (width / (scale * 2) >= desiredWidth && height / (scale * 2) >= desiredHeight) {
        scale = scale * 2;/*ww  w.ja v  a2  s  . c  o m*/
    }

    return scale;
}

From source file:com.goliathonline.android.kegbot.util.BitmapUtils.java

/**
 * Only call this method from the main (UI) thread. The {@link OnFetchCompleteListener} callback
 * be invoked on the UI thread, but image fetching will be done in an {@link AsyncTask}.
 *
 * @param cookie An arbitrary object that will be passed to the callback.
 *//*from  w w  w. ja  v  a2  s  . c  om*/
public static void fetchImage(final Context context, final String url,
        final BitmapFactory.Options decodeOptions, final Object cookie,
        final OnFetchCompleteListener callback) {
    new AsyncTask<String, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(String... params) {
            final String url = params[0];
            if (TextUtils.isEmpty(url)) {
                return null;
            }

            // First compute the cache key and cache file path for this URL
            File cacheFile = null;
            try {
                MessageDigest mDigest = MessageDigest.getInstance("SHA-1");
                mDigest.update(url.getBytes());
                final String cacheKey = bytesToHexString(mDigest.digest());
                if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                    cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Android"
                            + File.separator + "data" + File.separator + context.getPackageName()
                            + File.separator + "cache" + File.separator + "bitmap_" + cacheKey + ".tmp");
                }
            } catch (NoSuchAlgorithmException e) {
                // Oh well, SHA-1 not available (weird), don't cache bitmaps.
            }

            if (cacheFile != null && cacheFile.exists()) {
                Bitmap cachedBitmap = BitmapFactory.decodeFile(cacheFile.toString(), decodeOptions);
                if (cachedBitmap != null) {
                    return cachedBitmap;
                }
            }

            try {
                // TODO: check for HTTP caching headers
                final HttpClient httpClient = SyncService.getHttpClient(context.getApplicationContext());
                final HttpResponse resp = httpClient.execute(new HttpGet(url));
                final HttpEntity entity = resp.getEntity();

                final int statusCode = resp.getStatusLine().getStatusCode();
                if (statusCode != HttpStatus.SC_OK || entity == null) {
                    return null;
                }

                final byte[] respBytes = EntityUtils.toByteArray(entity);

                // Write response bytes to cache.
                if (cacheFile != null) {
                    try {
                        cacheFile.getParentFile().mkdirs();
                        cacheFile.createNewFile();
                        FileOutputStream fos = new FileOutputStream(cacheFile);
                        fos.write(respBytes);
                        fos.close();
                    } catch (FileNotFoundException e) {
                        Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e);
                    } catch (IOException e) {
                        Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e);
                    }
                }

                // Decode the bytes and return the bitmap.
                return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, decodeOptions);
            } catch (Exception e) {
                Log.w(TAG, "Problem while loading image: " + e.toString(), e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            callback.onFetchComplete(cookie, result);
        }
    }.execute(url);
}

From source file:tw.idv.gasolin.pycontw2012.util.BitmapUtils.java

/**
 * Only call this method from the main (UI) thread. The
 * {@link OnFetchCompleteListener} callback be invoked on the UI thread, but
 * image fetching will be done in an {@link AsyncTask}.
 * //  w  ww . j a v  a  2s  .c om
 * @param cookie
 *            An arbitrary object that will be passed to the callback.
 */
public static void fetchImage(final Context context, final String url,
        final BitmapFactory.Options decodeOptions, final Object cookie,
        final OnFetchCompleteListener callback) {
    new AsyncTask<String, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(String... params) {
            final String url = params[0];
            if (TextUtils.isEmpty(url)) {
                return null;
            }

            // First compute the cache key and cache file path for this URL
            File cacheFile = null;
            try {
                MessageDigest mDigest = MessageDigest.getInstance("SHA-1");
                mDigest.update(url.getBytes());
                final String cacheKey = bytesToHexString(mDigest.digest());
                if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                    cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Android"
                            + File.separator + "data" + File.separator + context.getPackageName()
                            + File.separator + "cache" + File.separator + "bitmap_" + cacheKey + ".tmp");
                }
            } catch (NoSuchAlgorithmException e) {
                // Oh well, SHA-1 not available (weird), don't cache
                // bitmaps.
            }

            if (cacheFile != null && cacheFile.exists()) {
                Bitmap cachedBitmap = BitmapFactory.decodeFile(cacheFile.toString(), decodeOptions);
                if (cachedBitmap != null) {
                    return cachedBitmap;
                }
            }

            try {
                // TODO: check for HTTP caching headers
                final HttpClient httpClient = SyncService.getHttpClient(context.getApplicationContext());
                final HttpResponse resp = httpClient.execute(new HttpGet(url));
                final HttpEntity entity = resp.getEntity();

                final int statusCode = resp.getStatusLine().getStatusCode();
                if (statusCode != HttpStatus.SC_OK || entity == null) {
                    return null;
                }

                final byte[] respBytes = EntityUtils.toByteArray(entity);

                // Write response bytes to cache.
                if (cacheFile != null) {
                    try {
                        cacheFile.getParentFile().mkdirs();
                        cacheFile.createNewFile();
                        FileOutputStream fos = new FileOutputStream(cacheFile);
                        fos.write(respBytes);
                        fos.close();
                    } catch (FileNotFoundException e) {
                        Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e);
                    } catch (IOException e) {
                        Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e);
                    }
                }

                // Decode the bytes and return the bitmap.
                return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, decodeOptions);
            } catch (Exception e) {
                Log.w(TAG, "Problem while loading image: " + e.toString(), e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            callback.onFetchComplete(cookie, result);
        }
    }.execute(url);
}

From source file:com.sat.sonata.MenuActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection.
    switch (item.getItemId()) {
    case R.id.stop:
        Log.d("SITTING", "Inside stop case");
        //stopService(new Intent(this, SonataService.class));
        return true;
    case R.id.recognise:
        String imagePath = getIntent().getStringExtra("image");
        getIntent().removeExtra("image");
        Log.d("SITTING", imagePath);

        HttpPost postRequest = new HttpPost("http://129.31.195.224:8080/picUpload");
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        try {//from   w w w  .  j a  va 2  s .com

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            Bitmap bitmap;
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            bitmap = BitmapFactory.decodeFile(imagePath, options);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 75, bos);
            byte[] data = bos.toByteArray();
            ByteArrayBody bab = new ByteArrayBody(data, "music.jpg");

            reqEntity.addPart("music", bab);

            postRequest.setEntity(reqEntity);
            HttpPost[] posts = new HttpPost[1];
            posts[0] = postRequest;

            GetImageTask getImageTask = new GetImageTask();
            getImageTask.execute(posts);

        } catch (Exception e) {
            Log.v("Exception in Image", "" + e);
            //                    reqEntity.addPart("picture", new StringBody(""));
        }

    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.image.oom.ImageUtil.java

public static Bitmap getBitMap(String fileFullName, int width, int height) throws Exception {
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inJustDecodeBounds = true;/*from  w w  w.ja v a  2 s.  c o  m*/
    FileInputStream fileInputStream = new FileInputStream(new File(fileFullName));
    BitmapFactory.decodeFile(fileFullName, opts);

    int be = 1;
    if (height != 0) {
        be = (int) (opts.outHeight / (float) width);
        if (be <= 0)
            be = 1;
    }
    if (width != 0) {
        be = (int) (opts.outWidth / (float) width);
        if (be <= 0)
            be = 1;
    }
    opts.inSampleSize = be;
    opts.inJustDecodeBounds = false;

    final Bitmap bm = BitmapFactory.decodeStream(fileInputStream, null, opts);

    fileInputStream.close();
    return bm;
}

From source file:com.ibuildapp.romanblack.FanWallPlugin.data.Statics.java

/**
 * Sets the downloaded avatar./*w  w  w. ja v a  2s .  c o  m*/
 *
 * @param filePath file path to avatar image
 */
public static Bitmap publishAvatar(String filePath) {
    Bitmap bitmap = null;

    if (!TextUtils.isEmpty(filePath)) {
        try {
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inSampleSize = 1;
            bitmap = BitmapFactory.decodeFile(filePath, opts);
            int size = 0;
            if (bitmap.getHeight() > bitmap.getWidth()) {
                size = bitmap.getWidth();
            } else {
                size = bitmap.getHeight();
            }
            Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(output);

            final int color = 0xff424242;
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, size, size);
            final RectF rectF = new RectF(rect);
            final float roundPx = 12;

            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(color);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            canvas.drawBitmap(bitmap, rect, rect, paint);

            bitmap.recycle();

            return output;
        } catch (Exception e) {

        }
    }
    return null;
}

From source file:com.truebanana.bitmap.BitmapUtils.java

public static Bitmap decodeFile(File file, int targetWidth, int targetHeight) {
    if (targetWidth > 1 && targetHeight > 1) {
        BitmapFactory.Options options = getBounds(file);
        options.inJustDecodeBounds = false;
        options.inSampleSize = getInSampleSize(options, targetWidth, targetHeight);
        return BitmapFactory.decodeFile(file.getPath(), options);
    } else {/*from   w  w w .jav a2s  .  c om*/
        return BitmapFactory.decodeFile(file.getPath());
    }
}

From source file:com.scanvine.android.util.SVDownloadManager.java

private boolean fetchDrawable(Context context, String urlString, File localFile) {
    try {//from  ww  w  .j av a  2s  .  c o  m
        File tempFile = new File("" + localFile + "_tmp");
        boolean fetched = fetchFile(context, urlString, tempFile);
        if (fetched) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile("" + tempFile, options);
            //Log.i(""+this, "Decoded file: size "+options.outHeight+"x"+options.outWidth);
            options.inSampleSize = calculateInSampleSize(options, 100, 100);
            options.inJustDecodeBounds = false;
            Bitmap bmp = BitmapFactory.decodeFile("" + tempFile, options);
            //Log.i(""+this, "Sampled file: size "+options.outHeight+"x"+options.outWidth);
            Bitmap resized = Bitmap.createScaledBitmap(bmp, 100, 100, true);
            FileOutputStream out = new FileOutputStream(localFile);
            resized.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.close();
            tempFile.delete();
        }
        return true;
    } catch (Exception ex) {
        Log.e("" + this, "fetchDrawable failed", ex);
        return false;
    }
}