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.example.office.ui.mail.MailItemFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case MailItemActivity.CAMERA_REQUEST_CODE:
        if (resultCode == Activity.RESULT_OK) {
            try {
                String currentPhotoPath = ((MailItemActivity) getActivity()).getCurrentPhotoPath();
                Bitmap bmp = BitmapFactory.decodeFile(currentPhotoPath);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bmp.compress(CompressFormat.JPEG, 100, stream);

                MailItem mail = (MailItem) getActivity().getIntent().getExtras()
                        .get(getString(R.string.intent_mail_key));
                Utility.showToastNotification("Starting file uploading");
                mId = mail.getId();/*from  w  w w  .  jav a2 s.  c  om*/
                mImageBytes = stream.toByteArray();
                mFilename = StringUtils.substringAfterLast(currentPhotoPath, "/");
                getMessageAndAttachData();
            } catch (Exception e) {
                Utility.showToastNotification("Error during getting image from camera");
            }

        }
        break;

    case MailItemActivity.SELECT_PHOTO:
        if (resultCode == Activity.RESULT_OK) {
            try {
                Uri selectedImage = data.getData();
                InputStream imageStream = getActivity().getContentResolver().openInputStream(selectedImage);
                MailItem mail = (MailItem) getActivity().getIntent().getExtras()
                        .get(getString(R.string.intent_mail_key));
                Utility.showToastNotification("Starting file uploading");
                mId = mail.getId();
                mImageBytes = IOUtils.toByteArray(imageStream);
                mFilename = selectedImage.getLastPathSegment();
                getMessageAndAttachData();
            } catch (Throwable t) {
                Utility.showToastNotification("Error during getting image from file");
            }
        }
        break;

    default:
        super.onActivityResult(requestCode, resultCode, data);
    }

}

From source file:com.example.cuisoap.agrimac.homePage.machineDetail.driverInfoFragment.java

public void setupData() {
    if (machineDetailData.drive_type.equals("1")) {
        drive_type.check(R.id.machine_drivetype_1);
        System.out.println(machineDetailData.driver_name);
        System.out.println(machineDetailData.driver_age);
        driver_name.setText(machineDetailData.driver_name);
        driver_age.setText(machineDetailData.driver_age);
        if (machineDetailData.driver_gender.equals("1")) {
            driver_gender.check(R.id.driver_male);
        } else/*from  www .  j a v  a 2  s. c  o  m*/
            driver_gender.check(R.id.driver_female);
        license_type.setText(machineDetailData.driver_license_type);
        String filename = img_path + machineDetailData.driver_license_filepath.replace('/', '_');
        File f = new File(filename);
        // File f=new File(machineDetailData.driver_license_filepath);
        System.out.println("driver_pic_url=" + machineDetailData.driver_license_filepath);
        if (!f.exists()) {
            //TODO g
            new NormalLoadPictrue().getPicture(machineDetailData.driver_license_filepath, license_pic);
        } else {
            System.out.println(machineDetailData.driver_license_filepath);
            Bitmap b = BitmapFactory.decodeFile(filename);
            license_pic.setImageBitmap(b);
            license_pic.setVisibility(View.VISIBLE);
        }
        license.setVisibility(View.GONE);
    } else {
        drive_type.check(R.id.machine_drivetype_2);
        driver_info.setVisibility(View.GONE);
    }

}

From source file:com.gfan.sbbs.utils.images.ImageManager.java

public Bitmap downloadImage2(String url) throws HttpException {
    Log.d(TAG, "[NEW]Fetching image: " + url);
    InputStream inStream = BBSOperator.getInstance().get(url).asStream();
    String file = writeToFile(inStream, getMd5(url));
    try {//from  ww w .j  av  a 2s.co  m
        inStream.close();
    } catch (IOException e) {
        e.printStackTrace();
        throw new HttpException(e.getMessage(), e);
    }
    Bitmap bitmap = BitmapFactory.decodeFile(file);
    if (null == bitmap) {
        Log.e(TAG, "here bitmap is null");
        Log.e(TAG, file);
    }
    bitmap = resizeBitmap(bitmap, IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT);
    return bitmap;
}

From source file:com.thx.bizcat.util.ImageDownloader.java

public Bitmap imageViewProcessing(String localImgUrl, String ServerImgUrl) {
    // 1. Cache Check
    Bitmap bm = getBitmapFromCache(localImgUrl);
    if (bm != null)
        return bm;

    // 2. File Check
    File file = new File(localImgUrl);
    if (file.exists()) {
        bm = BitmapFactory.decodeFile(file.getAbsolutePath());
        if (bm != null)
            return bm;
        else/* www . jav a  2 s .co m*/
            file.delete();
    } else {
        boolean b = file.mkdirs();
        b = file.delete();
        //b = dir.createNewFile();
    }

    // 3. Download Image
    try {
        URL url = new URL(ServerImgUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        InputStream is = conn.getInputStream();
        FileOutputStream fos = new FileOutputStream(localImgUrl);

        int len = conn.getContentLength();
        byte[] raster = new byte[len];

        int read = 0;
        while (true) {
            read = is.read(raster);
            if (read <= 0)
                break;
            fos.write(raster, 0, read);
        }

        is.close();
        fos.close();
        conn.disconnect();

        bm = BitmapFactory.decodeFile(localImgUrl);
        if (bm != null)
            return bm;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:www.image.ImageManager.java

/**
 * File -> ?Bitmap -> .//from w w  w .  j  av a2 s .c  om
 * @param file
 * @throws IOException
 */
public void put(File file, int quality, boolean forceOverride) throws IOException {
    if (!file.exists()) {
        return;
    }
    if (!forceOverride && contains(file.getPath())) {
        // Image already exists.
        return;
        // TODO: write to file if not present.
    }

    Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
    bitmap = resizeBitmap(bitmap, MAX_WIDTH, MAX_HEIGHT);

    if (bitmap == null) {
    } else {
        put(file.getPath(), bitmap, quality);
    }
}

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

Bitmap downloadBitmap(String url) {
    if (bitmapCachePath != null) {
        File file;//from   w w  w . ja  v a 2  s  . co  m
        String fileName;

        fileName = url.hashCode() + ".jpg";
        file = new File(bitmapCachePath, fileName);

        if (file.exists()) {
            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            sHardBitmapCache.remove(url);
            sHardBitmapCache.put(url, bitmap);
            return bitmap;
        }
    }

    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);
            client.close();
            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.

                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Bitmap.Config.RGB_565;
                options.inSampleSize = 1;
                // Bitmap bm = BitmapFactory.decodeStream(new
                // FlushedInputStream(inputStream), null, null);
                Bitmap bm = null;

                if (bitmapCachePath != null) {
                    File path = new File(bitmapCachePath);
                    if (!path.exists()) {
                        path.mkdirs();
                    }
                    File file;
                    file = new File(bitmapCachePath, url.hashCode() + ".jpg");

                    FileOutputStream fOut = new FileOutputStream(file);

                    int read = 0;
                    byte[] bytes = new byte[1024];

                    while ((read = inputStream.read(bytes)) != -1) {
                        fOut.write(bytes, 0, read);
                    }

                    // bm.compress(Bitmap.CompressFormat.JPEG, 50, fOut);
                    fOut.flush();
                    fOut.close();
                    String tmp = file.getCanonicalPath();
                    bm = BitmapFactory.decodeFile(file.getCanonicalPath(), options);
                    client.close();
                    return bm;
                } else {
                    client.close();
                    return BitmapFactory.decodeStream(inputStream, null, null);
                }
            } 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 {
        client.close();
    }
    return null;
}

From source file:cn.sqy.contacts.ui.ImageDownloader.java

Bitmap downloadBitmap(String url) {
    final int IO_BUFFER_SIZE = 4 * 1024;

    ////from w ww  .  j  a va 2  s. c o m
    String[] temp = url.split("/");
    String picname = temp[temp.length - 1];
    String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator
            + ContantsUtil.LOCALFOLDER;
    File file = new File(path + File.separator + picname);
    if (file.exists()) {
        return BitmapFactory.decodeFile(path + File.separator + picname);
    }

    // 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 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(inputStream);
                // Bug on slow connections, fixed in future release.
                Bitmap bmp = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
                ImageTools.storeInSD(bmp, path, picname);
                return bmp;
            } 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.battlelancer.seriesguide.util.ImageDownloader.java

Bitmap downloadBitmap(String url, boolean isDiskCaching) {

    File imagefile = null;/*from   ww w .  jav  a  2s  . c om*/
    if (isDiskCaching) {
        String filename = Integer.toHexString(url.hashCode()) + "." + CompressFormat.JPEG.name();
        imagefile = new File(mDiskCacheDir + "/" + filename);

        if (Utils.isExtStorageAvailable()) {
            // try to get bitmap from disk cache first
            if (imagefile.exists()) {
                // disk cache hit
                final Bitmap bitmap = BitmapFactory.decodeFile(imagefile.getAbsolutePath());
                if (bitmap != null) {
                    return bitmap;
                }
            }
        }
    }

    // if loading from disk fails, download it
    final 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(inputStream);
                // Bug on slow connections, fixed in future release.
                // Bitmap bitmap = BitmapFactory.decodeStream(new
                // FlushedInputStream(inputStream));

                // write directly to disk
                Bitmap bitmap;
                if (isDiskCaching && Utils.isExtStorageAvailable()) {
                    FileOutputStream outputstream = new FileOutputStream(imagefile);
                    Utils.copy(new FlushedInputStream(inputStream), outputstream);
                    outputstream.close();
                    bitmap = BitmapFactory.decodeFile(imagefile.getAbsolutePath());
                } else {
                    // if we have no external storage, decode directly
                    bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
                }

                // // TODO look if we can return the bitmap first, then save
                // in
                // // the background
                // if (Utils.isExtStorageAvailable()) {
                // // write the bitmap to the disk cache
                // FileOutputStream os = new FileOutputStream(imagefile);
                //
                // @SuppressWarnings("unused")
                // boolean isreconstructable =
                // bitmap.compress(CompressFormat.JPEG, 90, os);
                // os.close();
                // }

                return bitmap;
            } 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:jog.my.memory.gcm.ServerUtilities.java

/**
 * Uploads a file to the server./*from w ww . j a va 2s. c o m*/
 * @param context - Context of the app where the file is
 * @param serverUrl - URL of the server
 * @param uri - URI of the file
 * @return - response of posting the file to server
 */
public static String postFile(Context context, String serverUrl, Uri uri) { //TODO: Get the location sent up in here too!

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(serverUrl + "/upload");
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    //        //Create the FileBody
    //        final File file = new File(uri.getPath());
    //        FileBody fb = new FileBody(file);

    // deal with the file
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    Bitmap bitmap = BitmapFactory.decodeFile(getRealPathFromURI(uri, context));
    bitmap.compress(Bitmap.CompressFormat.JPEG, 75, byteArrayOutputStream);
    byte[] byteData = byteArrayOutputStream.toByteArray();
    //String strData = Base64.encodeToString(data, Base64.DEFAULT); // I have no idea why Im doing this
    ByteArrayBody byteArrayBody = new ByteArrayBody(byteData, "image"); // second parameter is the name of the image (//TODO HOW DO I MAKE IT USE THE IMAGE FILENAME?)

    builder.addPart("myFile", byteArrayBody);
    builder.addTextBody("foo", "test text");

    HttpEntity entity = builder.build();
    post.setEntity(entity);

    try {
        HttpResponse response = client.execute(post);
        Log.d(TAG, "The response code was: " + response.getStatusLine().getStatusCode());
    } catch (Exception e) {
        Log.d(TAG, "The image was not successfully uploaded.");
    }

    return null;

    //        HttpClient httpclient = new DefaultHttpClient();
    //        HttpPost httppost = new HttpPost(serverUrl+"/postFile.do");
    //
    //        InputStream stream = null;
    //        try {
    //            stream = context.getContentResolver().openInputStream(uri);
    //
    //            InputStreamEntity reqEntity = new InputStreamEntity(stream, -1);
    //
    //            httppost.setEntity(reqEntity);
    //
    //            HttpResponse response = httpclient.execute(httppost);
    //            Log.d(TAG,"The response code was: "+response.getStatusLine().getStatusCode());
    //            if (response.getStatusLine().getStatusCode() == 200) {
    //                // file uploaded successfully!
    //            } else {
    //                throw new RuntimeException("server couldn't handle request");
    //            }
    //            return response.toString();
    //        } catch (Exception e) {
    //            e.printStackTrace();
    //
    //            // handle error
    //        } finally {
    //            try {
    //                stream.close();
    //            }catch(IOException ioe){
    //                ioe.printStackTrace();
    //            }
    //        }
    //        return null;
}

From source file:org.blanco.techmun.android.MensajesActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 0 && resultCode == RESULT_OK) {
        Cursor c = managedQuery(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null,
                "_id = " + 1, null, null);
        if (c != null && c.moveToNext()) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();/*from  w ww  .  j  av a  2 s.com*/

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();

            attachImage = BitmapFactory.decodeFile(filePath);
            //Mark the button as image attached
            btnAddImage.setBackgroundColor(Color.YELLOW);
            Log.i("techmun", "selected image" + filePath + " Loaded.");

        }
        Log.d("techmun", "Returned from image pick");

    }
    super.onActivityResult(requestCode, resultCode, data);
}