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) 

Source Link

Document

Decode a file path into a bitmap.

Usage

From source file:com.c4mprod.utils.ImageDownloader.java

/**
 * @param url//w w  w.  ja  v a  2  s  . c  om
 *            The URL of the image that will be retrieved from the cache.
 * @return The cached bitmap or null if it was not found.
 */
private Bitmap getBitmapFromCache(String url) {

    if (mExternalStorageAvailable && url != null) {
        File f = new File(mfolder, URLEncoder.encode(url));

        if (f.exists()) {
            try {
                return BitmapFactory.decodeFile(f.getPath());

            } catch (Exception e) {
                // Log.e(Constants.PROJECT_TAG, "Error in retrieving picture", e);
                e.printStackTrace();
            }
        }
    }

    // First try the hard reference cache
    synchronized (sHardBitmapCache) {
        final Bitmap bitmap = sHardBitmapCache.get(url);
        if (bitmap != null) {
            // Bitmap found in hard cache
            // Move element to first position, so that it is removed last
            sHardBitmapCache.remove(url);
            sHardBitmapCache.put(url, bitmap);
            return bitmap;
        }
    }

    // Then try the soft reference cache
    try {
        SoftReference<Bitmap> bitmapReference = sSoftBitmapCache.get(url);
        if (bitmapReference != null) {
            final Bitmap bitmap = bitmapReference.get();
            if (bitmap != null) {
                // Bitmap found in soft cache
                return bitmap;
            } else {
                // Soft reference has been Garbage Collected
                sSoftBitmapCache.remove(url);
            }
        }
    } catch (Exception e) {
        return null;
    }

    return null;
}

From source file:com.expertiseandroid.lib.sociallib.connectors.TwitterConnector.java

/**
 * Sends a photo to TwitPic//w  ww  .ja va  2  s.c o  m
 * @param filePath the path of the picture
 * @param caption a caption associated with the picture
 * @return the url of the picture on TwitPic
 * @throws OAuthMessageSignerException
 * @throws OAuthExpectationFailedException
 * @throws OAuthCommunicationException
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 */
public String sendPhoto(String filePath, String caption)
        throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException,
        UnsupportedEncodingException, IOException, SAXException, ParserConfigurationException {
    Bitmap image = BitmapFactory.decodeFile(filePath);
    ReadableResponse response = Utils.postTwitpic(image, httpOauthConsumer, twitPicKey, caption);
    return reader.readUrl(response);
}

From source file:com.roamprocess1.roaming4world.ui.messages.MessageAdapter.java

public void downloadFile(String subject3, int flag) {
    String imageName, imageDirNumber;

    imageDirNumber = getNumber(subject3);
    imageName = getTimestamp(subject3);//from   w  ww  .  j ava2  s . c  o  m
    if (checkFile(imageDirNumber, imageName) == true) {
        if (flag == RECIEVED_IMAGE) {
            String p = fileDir + imageDirNumber + "/Recieved/" + imageName;
            Log.d("pp", p);
            try {
                Bitmap b = BitmapFactory.decodeFile(p);
                int[] size = messageActivity.getBitmapSize(b);
                b = Bitmap.createScaledBitmap(b, size[0], size[1], false);
                iv_recievedfile.setImageBitmap(b);
                // iv_recievedfile.setImageURI(Uri.parse(p));
            } catch (Exception e) {
                // TODO: handle exception
                iv_recievedfile.setImageResource(R.drawable.download_icon);
                setProgressBar(subject3);
            }
        } else if (flag == RECIEVED_VIDEO) {
            try {
                Bitmap b = BitmapFactory.decodeResource(context.getResources(), R.drawable.google_video_icon);
                iv_recievedfile.setImageBitmap(b);
            } catch (Exception e) {
                // TODO: handle exception
                iv_recievedfile.setImageResource(R.drawable.download_icon);
                setProgressBar(subject3);
            }
        } else if (flag == RECIEVED_AUDIO) {
            try {
                Bitmap b = BitmapFactory.decodeResource(context.getResources(), R.drawable.google_audio_icon);
                iv_recievedfile.setImageBitmap(b);
            } catch (Exception e) {
                // TODO: handle exception
                iv_recievedfile.setImageResource(R.drawable.download_icon);
                setProgressBar(subject3);
            }
        }
    } else {
        setProgressBar(subject3);
    }

}

From source file:com.akop.bach.ImageCache.java

public Bitmap getCachedBitmap(String imageUrl, CachePolicy cachePol) {
    if (imageUrl == null || imageUrl.length() < 1)
        return null;

    // Returns the cached image, or NULL if the image is not yet cached
    File file = getCacheFile(imageUrl, cachePol);

    // Return NULL if we don't have a cached copy
    if (!file.canRead())
        return null;

    if (cachePol != null && cachePol.expired(System.currentTimeMillis(), file.lastModified()))
        return null;

    try {//from  w ww.  ja  v  a2s.c  o m
        return BitmapFactory.decodeFile(file.getAbsolutePath());
    } catch (OutOfMemoryError e) {
        return null;
    } catch (Exception e) {
        if (App.getConfig().logToConsole()) {
            App.logv("error decoding %s", file.getAbsolutePath());
            e.printStackTrace();
        }

        return null;
    }
}

From source file:connection.ChaperOnConnection.java

private HttpPost GetPostHTTP(String email, String password, String firstname, String username, String imagePath,
        String street, String apartment, String city, String postal, String country, String lastname,
        String description, int rideType, double lattitude, double longitude, String phone, int availableseats,
        String licenseImage) {/*from  w  ww  .ja  v a 2  s . c o m*/
    Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
    Bitmap bitmap2 = BitmapFactory.decodeFile(licenseImage);
    HttpPost request = new HttpPost(REGISTER_URL);
    String param = "{\"phone\":\"" + phone + "\",\"email\":\"" + email + "\",\"password\": \"" + password
            + "\",\"username\": \"" + username + "\",\"availableSeats\":" + availableseats + ",\"type\": "
            + rideType + ",\"lattitude\": " + lattitude + ",\"longtitude\": " + longitude + ",\"street\": \""
            + street + "\",\"appartment\": \"" + apartment + "\",\"city\": \"" + city + "\",\"zip\": \""
            + postal + "\",\"country\": \"" + country + "\",\"lname\": \"" + lastname + "\",\"description\": \""
            + description + "\",\"fname\": \"" + firstname + "\"}";
    String BOUNDARY = "---------------------------41184676334";
    request.setHeader("enctype", "multipart/form-data; boundary=" + BOUNDARY);
    request.setHeader("app-id", "appid");
    request.setHeader("app-key", "appkey");

    MultipartEntityBuilder entity = MultipartEntityBuilder.create();

    try {
        entity.addPart("data", new StringBody(param));

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, bos);
        bitmap2.compress(Bitmap.CompressFormat.JPEG, 70, bos2);

        InputStream in = new ByteArrayInputStream(bos.toByteArray());
        InputStream in2 = new ByteArrayInputStream(bos2.toByteArray());

        ContentBody image = new InputStreamBody(in, "image/jpeg");
        ContentBody image2 = new InputStreamBody(in2, "image/jpeg");
        entity.addPart("image", image);
        entity.addPart("licenceimage", image2);

    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    request.setEntity(entity.build());
    return request;
}

From source file:com.roamprocess1.roaming4world.ui.messages.MessageAdapter.java

public void setImageOnRow(String msgSubject) {
    String imageName, imageDirNumber;
    imageDirNumber = getNumber(msgSubject);
    imageName = getTimestamp(msgSubject);
    if (checkFile(imageDirNumber, imageName) == true) {
        Bitmap b = BitmapFactory.decodeFile(fileDir + imageDirNumber + "/Recieved/" + imageName);
        iv_recievedfile.setImageBitmap(b);
    } else {/*from  w ww.  j  a v  a 2  s .c  om*/
        iv_recievedfile.setImageResource(R.drawable.logo);
        Log.d("error in download", "true");
    }
    try {
        if (pb_uploading != null) {
            pb_uploading.setVisibility(ProgressBar.GONE);
        }
    } catch (Exception e) {
        // TODO: handle exception
    }

}

From source file:com.raspi.chatapp.ui.chatting.SendImageFragment.java

/**
 * saves a copy in the internal storage. This may be used for displaying when
 * rendering the real image in background. As this is image is really low
 * quality it is loaded instantly (size is a couple bytes) you can load
 * this in the main thread while the background thread will do the heavy
 * loading task./* w w w  .j a va 2 s.c om*/
 *
 * @param context      the context used to get the localStorage
 * @param fileLocation the location of the file that is to be saved
 * @param id           the messageId of the imageMessage, for the file name
 * @param chatId       the chatId of the chat the image is from, for the file name
 */
private void saveImageCopy(Context context, String fileLocation, Long id, String chatId) {
    try {
        //old images bitmap
        Bitmap oldImg = BitmapFactory.decodeFile(fileLocation);
        // sample the height to 50 and maintain the aspect ratio
        float height = 50;
        float x = oldImg.getHeight() / height;
        float width = oldImg.getWidth() / x;

        // generate the destination file
        File destFile = new File(context.getFilesDir(), chatId + "-" + id + ".jpg");
        OutputStream out = new FileOutputStream(destFile);
        // generate the bitmap to compress to file
        Bitmap image = Bitmap.createScaledBitmap(oldImg, (int) width, (int) height, true);
        // compress the bitmap to file
        image.compress(Bitmap.CompressFormat.JPEG, 20, out);
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.MustacheMonitor.MustacheMonitor.StacheCam.java

/**
 * Return a scaled bitmap based on the target width and height
 *
 * @param imagePath//from   w ww.j a  va2 s  .c o m
 * @return
 */
private Bitmap getScaledBitmap(String imagePath) {
    // If no new width or height were specified return the original bitmap
    if (this.targetWidth <= 0 && this.targetHeight <= 0) {
        return BitmapFactory.decodeFile(imagePath);
    }

    // figure out the original width and height of the image
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(imagePath, options);

    // determine the correct aspect ratio
    int[] widthHeight = calculateAspectRatio(options.outWidth, options.outHeight);

    // Load in the smallest bitmap possible that is closest to the size we want
    options.inJustDecodeBounds = false;
    options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, this.targetWidth,
            this.targetHeight);
    Bitmap unscaledBitmap = BitmapFactory.decodeFile(imagePath, options);

    return Bitmap.createScaledBitmap(unscaledBitmap, widthHeight[0], widthHeight[1], true);
}

From source file:com.netcompss.ffmpeg4android_client.BaseVideo.java

public String getFileNameByUri(Context context, Uri uri) {
    String fileName = "unknown";// default fileName
    Uri filePathUri = uri;/*from w w w  .  j  a va2  s  . c o m*/
    if (uri.getScheme().toString().compareTo("content") == 0) {
        ParcelFileDescriptor parcelFileDescriptor;
        String filename = null;
        try {
            FileOutputStream fos = null;
            parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri, "r");
            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
            String extr = Environment.getExternalStorageDirectory().toString();
            File mFolder = new File(extr + "/CHURCH");
            if (!mFolder.exists()) {
                mFolder.mkdir();
            } else {
                mFolder.delete();
                mFolder.mkdir();
            }

            String s = "rough.png";

            File f = new File(mFolder.getAbsolutePath(), s);

            filename = f.getAbsolutePath();
            Log.d("f", filename);
            try {
                fos = new FileOutputStream(f);
                image.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {

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

                e.printStackTrace();
            }
            parcelFileDescriptor.close();
            return filename;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else if (uri.getScheme().compareTo("file") == 0) {
        fileName = filePathUri.getPath();
        File fill = new File(fileName);
        if (fill.exists()) {
            Log.d("exitst", "exist");
            ParcelFileDescriptor parcelFileDescriptor;
            String filename = null;
            FileOutputStream fos = null;
            Bitmap image = BitmapFactory.decodeFile(fileName);
            String extr = Environment.getExternalStorageDirectory().toString();
            File mFolder = new File(extr + "/CHURCH");
            if (!mFolder.exists()) {
                mFolder.mkdir();
            } else {
                mFolder.delete();
                mFolder.mkdir();
            }

            String s = "rough.png";

            File f = new File(mFolder.getAbsolutePath(), s);

            filename = f.getAbsolutePath();
            Log.d("f", filename);
            try {
                fos = new FileOutputStream(f);
                image.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {

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

                e.printStackTrace();
            }
        } else {
            Log.d("not file exitst", "not exist");
        }
        Log.d("file", "file");
    } else {
        fileName = filePathUri.getPath();
        Log.d("else", "else");
    }

    return fileName;

}