Example usage for android.graphics Bitmap recycle

List of usage examples for android.graphics Bitmap recycle

Introduction

In this page you can find the example usage for android.graphics Bitmap recycle.

Prototype

public void recycle() 

Source Link

Document

Free the native object associated with this bitmap, and clear the reference to the pixel data.

Usage

From source file:bruce.kk.imglibcompare.picasso.PicassoActivity.java

@OnClick({ R.id.btn_load_local, R.id.btn_load_url, R.id.btn_load_cancel })
public void onClick(View view) {
    switch (view.getId()) {
    case R.id.btn_load_local:
        Picasso.with(PicassoActivity.this).load(R.mipmap.ic_loading).into(ivImg);
        break;//from  w w  w  . j a va2 s  .co m
    case R.id.btn_load_url:
        // 
        //                Picasso.with(PicassoActivity.this)
        //                       .load(ImgConstant.IMG_URL)
        //                       .resize(80, 80)
        //                       .error(R.mipmap.ic_failed)
        //                       .into(ivImg);
        // 
        Picasso.Builder builder = new Picasso.Builder(PicassoActivity.this);
        builder.listener(new Picasso.Listener() {
            @Override
            public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
                LogDetails.d(" exception: " + exception);
            }
        });
        builder.build().load(ImgConstant.IMG_URL)
                //                       .load("http://dd.com/ssss.jpg")
                .placeholder(R.mipmap.ic_loading2).error(R.mipmap.ic_failed)
                //  tansform 
                .transform(new Transformation() {
                    @Override
                    public Bitmap transform(Bitmap source) {
                        RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(getResources(),
                                source);
                        drawable.setCornerRadius(50);
                        //                             drawable.setCircular(true); // ?
                        // ? 
                        int width = drawable.getIntrinsicWidth();
                        int height = drawable.getIntrinsicHeight();
                        // ??
                        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE
                                ? Bitmap.Config.ARGB_8888
                                : Bitmap.Config.RGB_565;
                        //  bitmap
                        Bitmap bitmap = Bitmap.createBitmap(width, height, config);
                        if (bitmap != source) {
                            source.recycle();
                        }
                        Canvas canvas = new Canvas(bitmap);
                        drawable.setBounds(0, 0, width, height);
                        drawable.draw(canvas);
                        return bitmap;
                    }

                    @Override
                    public String key() {
                        return "rounded";
                    }
                }).into(ivImg);
        break;
    case R.id.btn_load_cancel:
        Picasso.with(PicassoActivity.this).cancelRequest(ivImg);
        break;
    }
}

From source file:com.xgf.inspection.qrcode.google.zxing.client.CaptureActivity.java

private void clearCache() {
    new Thread(new Runnable() {

        @Override//from w w w  . j a v  a 2 s.c om
        public void run() {
            for (UploadValue uploadValue : mUploadValueList) {
                File file = new File(uploadValue.getFileLocalUrl());
                if (file.exists()) {
                    com.xgf.inspection.photo.utils.FileUtils.deleteAllFiles(file);
                }

                String filePath = uploadValue.getFileLocalUrl();
                if (filePath.contains("/ins/")) {
                    filePath = filePath.replace("/ins/", "/ins/fail/");
                    File failfile = new File(filePath);
                    if (failfile.exists()) {
                        com.xgf.inspection.photo.utils.FileUtils.deleteAllFiles(failfile);
                    }
                }
            }
            for (Bitmap bitmap : mBitmapList) {
                bitmap.recycle();
            }
        }
    }).start();

}

From source file:com.letsdoitworld.wastemapper.utils.ImageDownloader.java

Bitmap downloadBitmap(String url) {
    BitmapFactory.Options bfOptions = new BitmapFactory.Options();

    // 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 {//from  w w  w  . jav  a2  s. 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);
        if (url.contains("content")) {

            InputStream inputStream = null;

            //MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            bfOptions.inDither = false; //Disable Dithering mode

            bfOptions.inPurgeable = true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared

            bfOptions.inInputShareable = true; //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future

            bfOptions.inTempStorage = new byte[32 * 1024];

            Bitmap bitmap = null;

            try {
                inputStream = mContext.getContentResolver().openInputStream(Uri.parse(url));
                // return BitmapFactory.decodeStream(inputStream);
                // Bug on slow connections, fixed in future release.
                bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream), null, bfOptions);
                return rezise(bitmap);
            } catch (FileNotFoundException fnfe) {
                fnfe.printStackTrace();
            } catch (OutOfMemoryError out) {
                if (bitmap != null) {
                    bitmap.recycle();
                    bitmap = null;
                }

                out.printStackTrace();
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }

            //InputStream input = 
            //Bitmap bitmap = BitmapFactory.decodeFile(MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString(),bfOptions);

            Log.w(LOG_TAG, "sdcard 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.velia_systems.menuphoto.connection.ImageDownloader.java

/**
 * Same as download but the image is always downloaded and the cache is not used.
 * Kept private at the moment as its interest is not clear.
 *//*from w  ww  . ja  v a2  s .  co  m*/
private void forceDownload(String url, ImageView imageView, Bitmap bitmap, ProgressBar progress) {
    // State sanity: url is guaranteed to never be null in DownloadedDrawable and cache keys.
    if (url == null) {
        imageView.setImageDrawable(null);
        return;
    }

    if (cancelPotentialDownload(url, imageView)) {
        switch (mode) {
        case NO_ASYNC_TASK:
            bitmap = downloadBitmap(url);
            //                    Log.d("ImageDownloader", "Sizes: " + bitmap.getWidth() + "x" + bitmap.getHeight());
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();

            int destHeight = 100 * height / width;

            Bitmap bmp1 = Bitmap.createScaledBitmap(bitmap, 100, destHeight, false);
            bitmap.recycle();

            addBitmapToCache(url, bmp1);
            imageView.setImageBitmap(bmp1);
            progress.setVisibility(View.GONE);
            break;

        case NO_DOWNLOADED_DRAWABLE:
            imageView.setMinimumHeight(50);
            BitmapDownloaderTask task = new BitmapDownloaderTask(imageView, progress);
            task.execute(url);
            break;

        case CORRECT:
            task = new BitmapDownloaderTask(imageView, progress);
            DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task);
            imageView.setImageDrawable(downloadedDrawable);
            imageView.setMinimumHeight(50);
            task.execute(url);
            break;
        }
    }
}

From source file:com.xgf.inspection.qrcode.google.zxing.client.CaptureActivity.java

private void clearSucCache() {
    new Thread(new Runnable() {

        @Override/*from  w  ww . j av a 2 s .  c  o m*/
        public void run() {
            for (UploadValue uploadValue : mUploadValueSucList) {
                File file = new File(uploadValue.getFileLocalUrl());
                if (file.exists()) {
                    com.xgf.inspection.photo.utils.FileUtils.deleteAllFiles(file);
                }

                String filePath = uploadValue.getFileLocalUrl();
                if (filePath.contains("/ins/")) {
                    filePath = filePath.replace("/ins/", "/ins/fail/");
                }
                File failfile = new File(filePath);
                if (failfile.exists()) {
                    com.xgf.inspection.photo.utils.FileUtils.deleteAllFiles(failfile);
                }
            }

            for (Bitmap bitmap : mBitmapList) {
                bitmap.recycle();
            }

            mBitmapList.clear();
        }
    }).start();
}

From source file:com.adamas.client.android.MainActivity.java

protected Result decode(Uri uri) {
    try {/*from  w w w . j a  v a 2s. c  om*/
        InputStream inputStream = getContentResolver().openInputStream(uri);
        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
        if (bitmap == null) {
            return null;
        }
        int width = bitmap.getWidth(), height = bitmap.getHeight();
        int[] pixels = new int[width * height];
        bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
        bitmap.recycle();
        bitmap = null;
        RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
        BinaryBitmap bBitmap = new BinaryBitmap(new HybridBinarizer(source));
        MultiFormatReader reader = new MultiFormatReader();
        try {
            com.google.zxing.Result result = reader.decode(bBitmap);
            return result;
        } catch (Exception e) {
            return null;
        }
    } catch (FileNotFoundException e) {
        return null;
    }
}

From source file:gov.nasa.arc.geocam.geocam.GeoCamService.java

public boolean uploadImage(Uri uri, long id, Map<String, String> vars, int downsampleFactor) {
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    String serverUrl = settings.getString(GeoCamMobile.SETTINGS_SERVER_URL_KEY, "BOGUS");
    String serverUsername = settings.getString(GeoCamMobile.SETTINGS_SERVER_USERNAME_KEY, "BOGUS");
    String username = settings.getString(GeoCamMobile.SETTINGS_SERVER_USERNAME_KEY, "BOGUS");
    String password = settings.getString(GeoCamMobile.SETTINGS_SERVER_PASSWORD_KEY, "BOGUS");

    String postUrl;// ww w .java  2 s .  co  m
    if (password.equals("")) {
        // old style -- username in url
        postUrl = serverUrl + "/upload/" + serverUsername + "/";
    } else {
        // new style -- username will be in credentials
        postUrl = serverUrl + "/upload-m/";
    }

    Log.i(GeoCamMobile.DEBUG_ID, "Uploading image #" + String.valueOf(id));
    try {
        InputStream readJpeg = null;
        if (downsampleFactor == 1) {
            readJpeg = getContentResolver().openInputStream(uri);
        } else {
            InputStream readFullJpeg = getContentResolver().openInputStream(uri);
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inSampleSize = downsampleFactor;
            Bitmap bitmap = BitmapFactory.decodeStream(readFullJpeg, null, opts);
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
            bitmap.recycle();
            readJpeg = new ByteArrayInputStream(bytes.toByteArray());
        }

        Log.d(GeoCamMobile.DEBUG_ID, "Posting to URL " + postUrl);
        int out = HttpPost.post(postUrl, vars, "photo", String.valueOf(id) + ".jpg", readJpeg, username,
                password);

        Log.d(GeoCamMobile.DEBUG_ID, "POST response: " + (new Integer(out).toString()));

        setLastStatus(out);
        return (out == 200);
    } catch (FileNotFoundException e) {
        Log.e(GeoCamMobile.DEBUG_ID, "FileNotFoundException: " + e);
        return false;
    } catch (IOException e) {
        Log.e(GeoCamMobile.DEBUG_ID, "IOException: " + e);
        setLastStatus(-2); // our code for i/o error in upload
        return false;
    } catch (NullPointerException e) {
        Log.e(GeoCamMobile.DEBUG_ID, "NullPointerException: " + e);
        return false;
    }
}

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

/**
 * Bitmap./*from ww  w. j av  a  2s  .  c  o  m*/
 * 
 * @param file
 *            URL/PATH
 * @param bitmap
 * @param quality
 */
private void writeFile(String file, Bitmap bitmap, int quality) {
    if (bitmap == null) {
        Log.w(TAG, "Can't write file. Bitmap is null.");
        return;
    }

    BufferedOutputStream bos = null;
    try {
        //         String hashedUrl = getMd5(file);
        String hashedUrl = file;
        bos = new BufferedOutputStream(mContext.openFileOutput(hashedUrl, Context.MODE_PRIVATE));
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos); // PNG
        Log.d(TAG, "Writing file: " + file);
    } catch (IOException ioe) {
        Log.e(TAG, ioe.getMessage());
    } finally {
        try {
            if (bos != null) {
                bitmap.recycle();
                bos.flush();
                bos.close();
            }
            // bitmap.recycle();
        } catch (IOException e) {
            Log.e(TAG, "Could not close file.");
        }
    }
}

From source file:com.undatech.opaque.RemoteCanvas.java

void initializeSoftCursor() {
    Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.cursor);
    int w = bm.getWidth();
    int h = bm.getHeight();
    int[] tempPixels = new int[w * h];
    bm.getPixels(tempPixels, 0, w, 0, 0, w, h);
    // Set cursor rectangle as well.
    myDrawable.setCursorRect(pointer.getX(), pointer.getY(), w, h, 0, 0);
    // Set softCursor to whatever the resource is.
    myDrawable.setSoftCursor(tempPixels);
    bm.recycle();//from  w  w  w . j  av a2s.  c o  m
}