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.nextgis.maplib.map.RemoteTMSLayer.java

@Override
public Bitmap getBitmap(TileItem tile) {
    Bitmap ret;/* www .java 2 s . co  m*/
    // try to get tile from local cache
    File tilePath = new File(mPath, tile.toString("{z}/{x}/{y}" + TILE_EXT));
    if (tilePath.exists()
            && System.currentTimeMillis() - tilePath.lastModified() < DEFAULT_MAXIMUM_CACHED_FILE_AGE) {
        ret = BitmapFactory.decodeFile(tilePath.getAbsolutePath());
        if (ret != null) {
            return ret;
        }
    }

    if (!mNet.isNetworkAvailable()) { //return tile from cache
        ret = BitmapFactory.decodeFile(tilePath.getAbsolutePath());
        return ret;
    }
    // try to get tile from remote
    String url = tile.toString(getURLSubdomain());
    Log.d(TAG, "url: " + url);
    try {

        final HttpGet get = new HttpGet(url);

        //basic auth
        if (null != mLogin && mLogin.length() > 0 && null != mPassword && mPassword.length() > 0) {
            get.setHeader("Accept", "*/*");
            final String basicAuth = "Basic "
                    + Base64.encodeToString((mLogin + ":" + mPassword).getBytes(), Base64.NO_WRAP);
            get.setHeader("Authorization", basicAuth);
        }

        final DefaultHttpClient HTTPClient = mNet.getHttpClient();
        final HttpResponse response = HTTPClient.execute(get);

        // Check to see if we got success
        final org.apache.http.StatusLine line = response.getStatusLine();
        if (line.getStatusCode() != 200) {
            Log.d(TAG, "Problem downloading MapTile: " + url + " HTTP response: " + line);
            ret = BitmapFactory.decodeFile(tilePath.getAbsolutePath());
            return ret;
        }

        final HttpEntity entity = response.getEntity();
        if (entity == null) {
            Log.d(TAG, "No content downloading MapTile: " + url);
            ret = BitmapFactory.decodeFile(tilePath.getAbsolutePath());
            return ret;
        }

        FileUtil.createDir(tilePath.getParentFile());

        InputStream input = entity.getContent();
        OutputStream output = new FileOutputStream(tilePath.getAbsolutePath());
        byte data[] = new byte[IO_BUFFER_SIZE];

        FileUtil.copyStream(input, output, data, IO_BUFFER_SIZE);

        output.close();
        input.close();
        ret = BitmapFactory.decodeFile(tilePath.getAbsolutePath());
        return ret;

    } catch (IOException e) {
        Log.d(TAG, "Problem downloading MapTile: " + url + " Error: " + e.getLocalizedMessage());
    }

    ret = BitmapFactory.decodeFile(tilePath.getAbsolutePath());
    return ret;
}

From source file:com.rastating.droidbeard.net.SickbeardAsyncTask.java

protected Bitmap getShowBanner(long tvdbid, int cachedInSB) {
    Bitmap banner;//from   w  w w  .  j a  va2 s  . c om
    File cachedBanner = new File(getContext().getCacheDir(), String.valueOf(tvdbid) + ".png");
    if (cachedBanner.exists() && !cachedBanner.isDirectory()) {
        banner = BitmapFactory.decodeFile(cachedBanner.getAbsolutePath());
    } else {
        ArrayList<Pair<String, Object>> params = new ArrayList<Pair<String, Object>>();
        params.add(new Pair<String, Object>("tvdbid", tvdbid));
        banner = getBitmap("show.getbanner", params);

        if (cachedInSB == 1) {
            if (banner != null) {
                try {
                    FileOutputStream stream = new FileOutputStream(cachedBanner);
                    banner.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    stream.flush();
                    stream.close();
                } catch (Exception e) {
                    banner = getDefaultBanner();
                }
            }
        }

        if (banner == null) {
            banner = getDefaultBanner();
        }
    }

    return banner;
}

From source file:de.dmxcontrol.device.Entity.java

public Bitmap getImage(Context context) {
    try {//from  w ww  . j  ava2s  . c  o m
        File imgFile = new File(ImageStorageName + File.separator + mImage);
        if (imgFile.isFile()) {
            if (imgFile.exists()) {
                Bitmap bmp = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
                if (bmp.getHeight() > 128 || bmp.getWidth() > 128) {
                    bmp = Bitmap.createScaledBitmap(bmp, 128, 128, false);
                }
                return bmp;
            }
        }
    } catch (Exception e) {
    }
    // Replace this icon with something else
    return BitmapFactory.decodeResource(context.getResources(), R.drawable.device_new);
}

From source file:com.nextgis.mobile.map.RemoteTMSLayer.java

@Override
public Bitmap getBitmap(TileItem tile) {
    // try to get tile from local cache
    File tilePath = new File(mPath, tile.toString("{z}/{x}/{y}.tile"));
    if (tilePath.exists()
            && System.currentTimeMillis() - tilePath.lastModified() < DEFAULT_MAXIMUM_CACHED_FILE_AGE) {
        return BitmapFactory.decodeFile(tilePath.getAbsolutePath());
    }/*  ww  w  .j  ava  2  s .  c o m*/

    if (!mMap.isNetworkAvaliable())
        return null;
    // try to get tile from remote
    try {

        final HttpUriRequest head = new HttpGet(tile.toString(mURL));
        final HttpResponse response;
        response = mHTTPClient.execute(head);

        // Check to see if we got success
        final org.apache.http.StatusLine line = response.getStatusLine();
        if (line.getStatusCode() != 200) {
            Log.w(TAG, "Problem downloading MapTile: " + tile.toString(mURL) + " HTTP response: " + line);
            return null;
        }

        final HttpEntity entity = response.getEntity();
        if (entity == null) {
            Log.w(TAG, "No content downloading MapTile: " + tile.toString(mURL));
            return null;
        }

        FileUtil.createDir(tilePath.getParentFile());

        InputStream input = entity.getContent();
        OutputStream output = new FileOutputStream(tilePath.getAbsolutePath());
        byte data[] = new byte[IO_BUFFER_SIZE];

        FileUtil.copyStream(input, output, data, IO_BUFFER_SIZE);

        output.close();
        input.close();
        return BitmapFactory.decodeFile(tilePath.getAbsolutePath());

    } catch (IOException e) {
        Log.w(TAG, e.getLocalizedMessage());
    }
    return null;
}

From source file:com.jigarmjoshi.service.task.UploaderTask.java

private final boolean uploadEntryReport(Report entry) {
    if (entry == null || entry.getUploaded()) {
        return true;
    }/*from ww  w  .  j  ava2  s. c  o m*/
    boolean resultFlag = false;
    try {
        Log.i(UploaderTask.class.getSimpleName(), "uploading " + entry.getImageFileName());
        Bitmap bm = BitmapFactory.decodeFile(entry.getImageFileName());
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bm.compress(CompressFormat.JPEG, 60, bos);
        byte[] data = bos.toByteArray();
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(this.serverUrl + "/uploadEntryRecord");
        ByteArrayBody bab = new ByteArrayBody(data, "report.jpg");
        // File file= new File("/mnt/sdcard/forest.png");
        // FileBody bin = new FileBody(file);
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        reqEntity.addPart("lat", new StringBody(Utility.encode(entry.getLat())));
        reqEntity.addPart("lon", new StringBody(Utility.encode(entry.getLon())));
        reqEntity.addPart("priority", new StringBody(Utility.encode(entry.getPriority())));
        reqEntity.addPart("fileName", new StringBody(Utility.encode(entry.getImageFileName())));
        reqEntity.addPart("reporterId", new StringBody(Utility.encode(entry.getId())));
        reqEntity.addPart("uploaded", bab);
        postRequest.setEntity(reqEntity);
        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String sResponse;
        StringBuilder responseString = new StringBuilder();

        while ((sResponse = reader.readLine()) != null) {
            responseString = responseString.append(sResponse);
        }
        Log.i(UploaderTask.class.getSimpleName(), responseString.toString());
        if ("SUCCESS".equalsIgnoreCase(responseString.toString())) {
            resultFlag = true;
            if (entry.getImageFileName() != null) {
                File imageFileToDelete = new File(entry.getImageFileName());
                boolean deleted = imageFileToDelete.delete();

                if (deleted) {
                    Log.i(UploaderTask.class.getSimpleName(), "deleted = ?" + deleted);
                    MediaScannerConnection.scanFile(context, new String[] {

                            imageFileToDelete.getAbsolutePath() },

                            null, new MediaScannerConnection.OnScanCompletedListener() {

                                public void onScanCompleted(String path, Uri uri)

                            {

                                }

                            });

                }
            }
        }

    } catch (Exception ex) {
        Log.e(UploaderTask.class.getSimpleName(), "failed to upload", ex);
        resultFlag = false;
    }
    return resultFlag;
}

From source file:com.mappn.gfan.ui.SplashActivity.java

private void initSplashBg() {

    File splashFile = new File(getApplicationContext().getCacheDir(), "splash.png");

    if (splashFile.exists()) {
        Bitmap bmp = BitmapFactory.decodeFile(splashFile.getAbsolutePath());
        if (bmp != null) {
            setSplashBitmap(bmp);//  w  w  w .  ja va2 s.  c  om
            return;
        }
    }
    // Splash
    setSplashBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.splash));
    mSession.setSplashTime(0);
}

From source file:at.ac.uniklu.mobile.sportal.util.Utils.java

/**
 * Loads a bitmap for the network or from a cached file, if it has already been downloaded before. If the file
 * is loaded for the first time, it is written to the cache to be available next time.
 * //from w w  w. j a v a 2  s . c o  m
 * @param context
 * @param sourceUrl
 * @param cacheFileName
 * @return a bitmap or null if something went wrong
 */
public static Bitmap downloadBitmapWithCache(Context context, String sourceUrl, String cacheFileName)
        throws Exception {
    Bitmap bitmap = null;
    File cacheFile = new File(context.getCacheDir(), cacheFileName);

    boolean cached = cacheFile.exists();
    boolean cachedValid = cached && cacheFile.lastModified() > (System.currentTimeMillis() - MILLIS_PER_WEEK);

    if (cached && cachedValid) {
        // the requested file is cached, load it
        Log.d(TAG, "loading cached file: " + cacheFileName);
        bitmap = BitmapFactory.decodeFile(cacheFile.getAbsolutePath());
    } else {
        // the requested file is not cached, download it from the network
        Log.d(TAG, "file " + (cachedValid ? "too old" : "not cached") + ", downloading: " + sourceUrl);
        byte[] data = downloadFile(sourceUrl, 3);
        if (data != null) {
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            if (bitmap != null) {
                // the download succeeded, cache the file so it is available next time
                FileOutputStream out = new FileOutputStream(cacheFile);
                out.write(data, 0, data.length);
                out.flush();
                out.close();
            } else {
                Log.e(TAG, "failed to download bitmap, may be an unsupported format: " + sourceUrl);
            }
        }
    }

    return bitmap;
}

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

public void imageViewProcessing(String localImgUrl, String ServerImgUrl, ImageView imageView) {
    //1.Cache Memory?  ? 
    Bitmap bitmap = getBitmapFromCache(localImgUrl);

    if (bitmap == null) {

        //? ?  ?  ?
        File file = new File(localImgUrl);
        if (file.exists()) {
            Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
            if (bm != null)
                imageView.setImageBitmap(bm);
            else// w w w  .ja va  2 s.  co  m
                file.delete();
        } else {
            try {
                //? ?   
                URL url = new URL(ServerImgUrl);

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                //? : Input Stream? ? ??  ? (?    ? ? )
                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();

                //? ? 
                Bitmap bm = BitmapFactory.decodeFile(localImgUrl);
                if (bm != null)
                    imageView.setImageBitmap(bm);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } else {
        imageView.setImageBitmap(bitmap);
    }
}

From source file:vn.evolus.droidreader.util.ImageCache.java

public synchronized Bitmap get(Object key) {
    String imageUrl = (String) key;
    Bitmap bitmap = cache.get(imageUrl);

    if (bitmap != null) {
        // 1st level cache hit (memory)
        return bitmap;
    }//from ww  w  .jav a  2s  .  c o m

    File imageFile = getImageFile(imageUrl);
    if (imageFile.exists()) {
        // 2nd level cache hit (disk)
        try {
            bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
        } catch (Throwable e) {
        }

        if (bitmap == null) {
            // treat decoding errors as a cache miss
            return null;
        }
        cache.put(imageUrl, bitmap);
        return bitmap;
    }

    // cache miss
    return null;
}

From source file:com.binomed.showtime.android.util.images.ImageDownloader.java

private Bitmap getFileDrawable(String url) {
    Bitmap image = null;//w ww.  jav  a2 s  . c  o  m
    String finalFileName = url.substring(url.lastIndexOf("/"), url.length());
    try {
        File root = Environment.getExternalStorageDirectory();
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            File imageFile = new File(root,
                    new StringBuilder(CineShowtimeCst.FOLDER_POSTER).append(getFileName(url)).toString());
            Log.d(LOG_TAG, "Try getting file : " + imageFile.getAbsolutePath());
            if (imageFile.exists()) {
                image = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
            }
        } else {
            Log.d(LOG_TAG, "SD card unmounted : " + url);

        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "Error creating file", e);
    }

    if (image != null) {
        addBitmapToCache(url, image);
    }

    return image;
}