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:com.MustacheMonitor.MustacheMonitor.StacheCam.java

/**
 * Cleans up after picture taking. Checking for duplicates and that kind of stuff.
 * @param newImage/*from   www.  j  a  v  a  2  s .c  o m*/
 */
private void cleanup(int imageType, Uri oldImage, Uri newImage, Bitmap bitmap) {
    if (bitmap != null) {
        bitmap.recycle();
    }

    // Clean up initial camera-written image file.
    (new File(FileUtils.stripFileProtocol(oldImage.toString()))).delete();

    checkForDuplicateImage(imageType);
    // Scan for the gallery to update pic refs in gallery
    if (this.saveToPhotoAlbum && newImage != null) {
        this.scanForGallery(newImage);
    }

    System.gc();
}

From source file:com.example.android.camera.CameraActivity.java

@Override
protected void onResume() {
    super.onResume();

    Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {

        @Override//from www  .ja  v a 2s. c o  m
        public void onPreviewFrame(byte[] data, Camera camera) {

            if (notRequesting && mPreview.faces.size() >= 1 && imageFormat == ImageFormat.NV21) {

                // Block Request.
                notRequesting = false;

                try {
                    Camera.Parameters parameters = camera.getParameters();
                    Size size = parameters.getPreviewSize();

                    textServerView.setText("Preparing Image to send");
                    YuvImage previewImg = new YuvImage(data, parameters.getPreviewFormat(), size.width,
                            size.height, null);
                    pWidth = previewImg.getWidth();
                    pHeight = previewImg.getHeight();

                    Log.d("face View", "Width: " + pWidth + " x Height: " + pHeight);
                    prepareMatrix(matrix, 0, pWidth, pHeight);
                    List<Rect> foundFaces = getFaces();

                    for (Rect cRect : foundFaces) {
                        // Cropping
                        ByteArrayOutputStream bao = new ByteArrayOutputStream();
                        previewImg.compressToJpeg(cRect, 100, bao);
                        byte[] mydata = bao.toByteArray();

                        // Resizing
                        ByteArrayOutputStream sbao = new ByteArrayOutputStream();
                        Bitmap bm = BitmapFactory.decodeByteArray(mydata, 0, mydata.length);
                        Bitmap sbm = Bitmap.createScaledBitmap(bm, 100, 100, true);
                        bm.recycle();
                        sbm.compress(Bitmap.CompressFormat.JPEG, 100, sbao);
                        byte[] mysdata = sbao.toByteArray();

                        RequestParams params = new RequestParams();
                        params.put("upload", new ByteArrayInputStream(mysdata), "tmp.jpg");

                        textServerView.setText("Sending Image to the Server");

                        FaceMatchClient.post(":8080/match", params, new JsonHttpResponseHandler() {
                            @Override
                            public void onSuccess(JSONArray result) {
                                Log.d("face onSuccess", result.toString());

                                try {
                                    JSONObject myJson = (JSONObject) result.get(0);
                                    float dist = (float) Double.parseDouble(myJson.getString("dist"));
                                    Log.d("distance", "" + dist);
                                    int level = (int) ((1 - dist) * 100);
                                    if (level > previousMatchLevel) {
                                        textView.setText("Match " + level + "% with " + myJson.getString("name")
                                                + " <" + myJson.getString("email") + "> ");

                                        loadImage(myJson.getString("classes"), myJson.getString("username"));
                                    }

                                    previousMatchLevel = level;
                                    trialCounter++;

                                    if (trialCounter < 100 && level < 74) {
                                        textServerView.setText("Retrying...");
                                        notRequesting = true;
                                    } else if (trialCounter == 100) {
                                        textServerView.setText("Fail...");
                                    } else {
                                        textServerView.setText("Found Good Match? If not try again!");
                                        fdButtonClicked = false;
                                        trialCounter = 0;
                                        previousMatchLevel = 0;
                                        mCamera.stopFaceDetection();
                                        button.setText("StartFaceDetection");
                                    }

                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }

                                //                                        informationView.showInfo(myJson);
                            }

                        });
                    }

                    textServerView.setText("POST Sent");
                    textServerView.setText("Awaiting for response");

                } catch (Exception e) {
                    e.printStackTrace();
                    textServerView.setText("Error AsyncPOST");
                }
            }
        }
    };

    // Open the default i.e. the first rear facing camera.
    mCamera = Camera.open();
    mCamera.setPreviewCallback(previewCallback);

    // To use front camera
    //        mCamera = Camera.open(CameraActivity.getFrontCameraId());
    mPreview.setCamera(mCamera);
    parameters = mCamera.getParameters();
    imageFormat = parameters.getPreviewFormat();
    PreviewSize = parameters.getPreviewSize();
}

From source file:aerizostudios.com.cropshop.MainActivity.java

public void Send(Bitmap imgbitmap) {
    try {//  ww  w .j av  a  2s.  c o m
        //Write file
        String filename = "bitmap.png";
        FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
        imgbitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);

        //Cleanup
        stream.close();
        imgbitmap.recycle();
        //Pop intent
        Intent in1 = new Intent(this, CropActivity.class);
        in1.putExtra("image", filename);
        startActivity(in1);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.android.contacts.common.ContactPhotoManager.java

/**
 * If necessary, decodes bytes stored in the holder to Bitmap.  As long as the
 * bitmap is held either by {@link #mBitmapCache} or by a soft reference in
 * the holder, it will not be necessary to decode the bitmap.
 *///from   w  ww .j  a  v  a2s. c  om
private static void inflateBitmap(BitmapHolder holder, int requestedExtent) {
    final int sampleSize = BitmapUtil.findOptimalSampleSize(holder.originalSmallerExtent, requestedExtent);
    byte[] bytes = holder.bytes;
    if (bytes == null || bytes.length == 0) {
        return;
    }

    if (sampleSize == holder.decodedSampleSize) {
        // Check the soft reference.  If will be retained if the bitmap is also
        // in the LRU cache, so we don't need to check the LRU cache explicitly.
        if (holder.bitmapRef != null) {
            holder.bitmap = holder.bitmapRef.get();
            if (holder.bitmap != null) {
                return;
            }
        }
    }

    try {
        Bitmap bitmap = BitmapUtil.decodeBitmapFromBytes(bytes, sampleSize);

        // TODO: As a temporary workaround while framework support is being added to
        // clip non-square bitmaps into a perfect circle, manually crop the bitmap into
        // into a square if it will be displayed as a thumbnail so that it can be cropped
        // into a circle.
        final int height = bitmap.getHeight();
        final int width = bitmap.getWidth();

        // The smaller dimension of a scaled bitmap can range from anywhere from 0 to just
        // below twice the length of a thumbnail image due to the way we calculate the optimal
        // sample size.
        if (height != width && Math.min(height, width) <= mThumbnailSize * 2) {
            final int dimension = Math.min(height, width);
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, dimension, dimension);
        }
        // make bitmap mutable and draw size onto it
        if (DEBUG_SIZES) {
            Bitmap original = bitmap;
            bitmap = bitmap.copy(bitmap.getConfig(), true);
            original.recycle();
            Canvas canvas = new Canvas(bitmap);
            Paint paint = new Paint();
            paint.setTextSize(16);
            paint.setColor(Color.BLUE);
            paint.setStyle(Style.FILL);
            canvas.drawRect(0.0f, 0.0f, 50.0f, 20.0f, paint);
            paint.setColor(Color.WHITE);
            paint.setAntiAlias(true);
            canvas.drawText(bitmap.getWidth() + "/" + sampleSize, 0, 15, paint);
        }

        holder.decodedSampleSize = sampleSize;
        holder.bitmap = bitmap;
        holder.bitmapRef = new SoftReference<Bitmap>(bitmap);
        if (DEBUG) {
            Log.d(TAG, "inflateBitmap " + btk(bytes.length) + " -> " + bitmap.getWidth() + "x"
                    + bitmap.getHeight() + ", " + btk(bitmap.getByteCount()));
        }
    } catch (OutOfMemoryError e) {
        // Do nothing - the photo will appear to be missing
    }
}

From source file:com.perm.DoomPlay.PlayingService.java

private RemoteViews getNotifViews(int layoutId) {
    RemoteViews views = new RemoteViews(getPackageName(), layoutId);

    Audio audio = audios.get(indexCurrentTrack);

    views.setTextViewText(R.id.notifTitle, audio.getTitle());
    views.setTextViewText(R.id.notifArtist, audio.getArtist());

    Bitmap cover = AlbumArtGetter.getBitmapFromStore(audio.getAid(), this);

    if (cover == null) {
        Bitmap tempBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.fallback_cover);
        views.setImageViewBitmap(R.id.notifAlbum, tempBitmap);
        tempBitmap.recycle();
    } else {//ww w  . ja  va2 s .co m
        //TODO: java.lang.IllegalArgumentException: RemoteViews for widget update exceeds
        // maximum bitmap memory usage (used: 3240000, max: 2304000)
        // The total memory cannot exceed that required to fill the device's screen once
        try {
            views.setImageViewBitmap(R.id.notifAlbum, cover);
        } catch (IllegalArgumentException e) {
            Bitmap tempBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.fallback_cover);
            views.setImageViewBitmap(R.id.notifAlbum, tempBitmap);
            tempBitmap.recycle();
        } finally {
            cover.recycle();
        }
    }

    views.setImageViewResource(R.id.notifPlay, isPlaying ? R.drawable.widget_pause : R.drawable.widget_play);

    ComponentName componentName = new ComponentName(this, PlayingService.class);

    Intent intentPlay = new Intent(actionPlay);
    intentPlay.setComponent(componentName);
    views.setOnClickPendingIntent(R.id.notifPlay, PendingIntent.getService(this, 0, intentPlay, 0));

    Intent intentNext = new Intent(actionNext);
    intentNext.setComponent(componentName);
    views.setOnClickPendingIntent(R.id.notifNext, PendingIntent.getService(this, 0, intentNext, 0));

    Intent intentPrevious = new Intent(actionPrevious);
    intentPrevious.setComponent(componentName);
    views.setOnClickPendingIntent(R.id.notifPrevious, PendingIntent.getService(this, 0, intentPrevious, 0));

    Intent intentClose = new Intent(actionClose);
    intentClose.setComponent(componentName);
    views.setOnClickPendingIntent(R.id.notifClose, PendingIntent.getService(this, 0, intentClose, 0));

    return views;
}

From source file:com.intel.xdk.camera.Camera.java

private void savePicture(final String outputFile, final int quality, final boolean isPNG) {
    //busy could be false if activity had been stopped
    busy = true;//from w ww .ja v a2  s  .com

    try {

        String dir = pictureDir();
        File dirFile = new File(dir);
        if (!dirFile.exists())
            dirFile.mkdirs();
        String baseName = getNextPictureFile(isPNG);
        String filePath = String.format("%1$s/%2$s", dir, baseName);

        try {
            if (debug)
                System.out.println("AppMobiCamera.takePicture: file = " + filePath);

            OutputStream out = new BufferedOutputStream(new FileOutputStream(filePath), 0x8000);

            Bitmap bitMap = BitmapFactory.decodeFile(outputFile);
            if (bitMap == null || !bitMap
                    .compress((isPNG ? Bitmap.CompressFormat.PNG : Bitmap.CompressFormat.JPEG), 70, out)) {
                throw new IOException("Error converting to PNG");
            }

            bitMap.recycle();
            out.close();

            fireJSEvent("camera.internal.picture.add", true, null,
                    new String[] { String.format("ev.filename='%1$s';", baseName) });
            fireJSEvent("camera.picture.add", true, null,
                    new String[] { String.format("ev.filename='%1$s';", baseName) });

            callbackContext.success("");
        } catch (IOException e) {
            postAddError(baseName);
            if (debug)
                System.out.println("AppMobiCamera.takePicture err: " + e.getMessage());
        } finally {
            callbackContext = null;
            busy = false;
        }
    } catch (Exception e) {
        //sometimes a NPE occurs after resuming, catch it here but do nothing
        if (Debug.isDebuggerConnected())
            Log.e("[intel.xdk]", "handled camera resume NPE:\n" + e.getMessage(), e);
    }
}

From source file:com.acceleratedio.pac_n_zoom.AnimActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_anm);
    orgnlImageView = (ImageView) findViewById(R.id.imageView);
    orgnlImageView.setMaxHeight(800);/*  w w  w  .ja  v a  2s .  c o m*/
    orgnlImageView.setMaxWidth(600);
    crt_ctx = this;

    BitmapFactory.Options bmp_opt = new BitmapFactory.Options();
    bmp_opt.inTargetDensity = DisplayMetrics.DENSITY_DEFAULT;

    // - Now we need to set the GUI ImageView data with data read from the picked file.
    DcodRszdBmpFil dcodRszdBmpFil = new DcodRszdBmpFil();
    Bitmap bmp = dcodRszdBmpFil.DcodRszdBmpFil(SelectImageActivity.orgFil, bmp_opt);

    // Now we need to set the GUI ImageView data with the orginal file selection.
    orgnlImageView.setImageBitmap(bmp);
    orgnl_iv_wdth = bmp.getWidth();
    orgnl_iv_hght = bmp.getHeight();
    final RelativeLayout rel_anm_lo = (RelativeLayout) findViewById(R.id.activity_anm_lo);
    scaleGestureDetector = new ScaleGestureDetector(this, new simpleOnScaleGestureListener());

    orgnlImageView.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if (event.getPointerCount() > 1 || flgInScale) {

                scaleGestureDetector.onTouchEvent(event);
                return true;
            }

            int end_hrz;
            int end_vrt;
            final int pointerIndex;

            switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:

                pointerIndex = MotionEventCompat.getActionIndex(event);
                bgn_hrz = (int) MotionEventCompat.getX(event, pointerIndex);
                bgn_vrt = (int) MotionEventCompat.getY(event, pointerIndex);

                String log_str = "Beginning coordinates: Horz = " + String.valueOf(bgn_hrz) + "; Vert = "
                        + String.valueOf(bgn_vrt);

                Log.d("OnTouchListener", log_str);
                orlp = (RelativeLayout.LayoutParams) orgnlImageView.getLayoutParams();
                bgn_top = (int) orlp.topMargin;
                bgn_lft = (int) orlp.leftMargin;

                // To prevent an initial jump of the magnifier, aposX and aPosY must
                // have the values from the magnifier frame
                if (aPosX == 0)
                    aPosX = orgnlImageView.getX();
                if (aPosY == 0)
                    aPosY = orgnlImageView.getY();
                break;

            case MotionEvent.ACTION_MOVE:

                pointerIndex = MotionEventCompat.getActionIndex(event);
                float crt_hrz = MotionEventCompat.getX(event, pointerIndex);
                float crt_vrt = MotionEventCompat.getY(event, pointerIndex);
                final float dx = crt_hrz - bgn_hrz;
                final float dy = crt_vrt - bgn_vrt;
                aPosX += dx;
                aPosY += dy;
                orgnlImageView.setX(aPosX);
                orgnlImageView.setY(aPosY);

                log_str = "Current Position: Horz = " + String.valueOf(crt_hrz) + "; Vert = "
                        + String.valueOf(crt_vrt);

                Log.d("OnTouchListener", log_str);

                break;

            case MotionEvent.ACTION_UP:

                pointerIndex = MotionEventCompat.getActionIndex(event);
                end_hrz = (int) MotionEventCompat.getX(event, pointerIndex);
                end_vrt = (int) MotionEventCompat.getY(event, pointerIndex);
            }

            rel_anm_lo.invalidate();
            return true;
        }
    });

    sav_anm_btn = (Button) findViewById(R.id.sav_btn);

    sav_anm_btn.setOnClickListener(new View.OnClickListener() {

        public void onClick(View vw) {

            onClickFlg = 1;
            RelativeLayout rel_anm_lo = (RelativeLayout) findViewById(R.id.activity_anm_lo);
            rel_anm_lo.removeView(vw);
            Bitmap tnBmp = getWrtBmp("thumbnail", rel_anm_lo, 40);
            tnBmp.recycle();
            int vw_nmbr = anmViews.size();

            for (int vw_mbr = 1; vw_mbr < vw_nmbr; vw_mbr += 1) {

                anim_view = anmViews.get(vw_mbr);

                if (anim_view != null) {

                    Animation crt_anm = anim_view.getAnimation();

                    if (crt_anm != null)
                        crt_anm.cancel();

                    anim_view.setAnimation(null);
                    rel_anm_lo.removeView(anim_view);

                    // Garbage collect the bitmap
                    Drawable drawable = anim_view.getDrawable();

                    if (drawable instanceof BitmapDrawable) {
                        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
                        Bitmap anim_bmp = bitmapDrawable.getBitmap();
                        anim_bmp.recycle();
                    }
                }
            }

            Bitmap orgnlImageBmp = getWrtBmp("bgimg", rel_anm_lo, 90);
            orgnlImageWdth = Integer.toString(orgnlImageBmp.getWidth());
            orgnlImageHght = Integer.toString(orgnlImageBmp.getHeight());
            anmViews.clear();
            unbindDrawables(rel_anm_lo);
            ((RelativeLayout) rel_anm_lo).removeAllViews();
            orgnlImageBmp.recycle();
            crt_ctx = null;
            orgnlImageView = null;

            Intent intent = new Intent(AnimActivity.this, com.acceleratedio.pac_n_zoom.SaveAnmActivity.class);

            startActivity(intent);
        }
    });

    progress = ProgressDialog.show(crt_ctx, "Loading the animation", "dialog message", true);
    GetRequest get_svg_img = new GetRequest();
    get_svg_img.execute("");
}

From source file:com.irccloud.android.activity.PastebinsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= 21) {
        Bitmap cloud = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        setTaskDescription(new ActivityManager.TaskDescription(getResources().getString(R.string.app_name),
                cloud, 0xFFF2F7FC));//from  www.j  a v  a  2  s .  c o  m
        cloud.recycle();
    }

    setContentView(R.layout.ignorelist);

    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
        getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar));
        getSupportActionBar().setElevation(0);
    }

    if (savedInstanceState != null && savedInstanceState.containsKey("adapter")) {
        try {
            page = savedInstanceState.getInt("page");
            Pastebin[] pastebins = (Pastebin[]) savedInstanceState.getSerializable("adapter");
            for (Pastebin p : pastebins) {
                adapter.addPastebin(p);
            }
            adapter.notifyDataSetChanged();
        } catch (Exception e) {
            page = 0;
            adapter.clear();
        }
    }

    footer = getLayoutInflater().inflate(R.layout.messageview_header, null);
    ListView listView = (ListView) findViewById(android.R.id.list);
    listView.setAdapter(adapter);
    listView.addFooterView(footer);
    listView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView absListView, int i) {

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (canLoadMore && firstVisibleItem + visibleItemCount > totalItemCount - 4) {
                canLoadMore = false;
                new FetchPastebinsTask().execute((Void) null);
            }
        }
    });
    listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            final Pastebin p = (Pastebin) adapter.getItem(i);

            Intent intent = new Intent(PastebinsActivity.this, PastebinViewerActivity.class);
            intent.setData(Uri.parse(p.url + "?id=" + p.id + "&own_paste=" + (p.own_paste ? "1" : "0")));
            startActivity(intent);
        }
    });

    Toast.makeText(this, "Tap a pastebin to view full text with syntax highlighting", Toast.LENGTH_LONG).show();
}

From source file:com.example.research.whatis.MainActivity.java

public void StoreImage(Context mContext, Bitmap bm) {
    //        Toast.makeText(this, "Storing image....", Toast.LENGTH_LONG).show();
    Log.d("API", "Stroging image " + OCRedText);
    System.out.println("Storing image...: " + OCRedText);

    try {//from w  w  w. j  a  v  a 2s . co  m

        FileOutputStream out = new FileOutputStream(sdImageMainDirectory.getPath());
        bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
        bm.recycle();
        // cleaning up
        //
        //            bm = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), imageLoc);
        //            FileOutputStream out = new FileOutputStream(imageDir);
        //            bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
        //            bm.recycle();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.appbase.androidquery.callback.BitmapAjaxCallback.java

private static Bitmap rotate(String path, Bitmap bm) {

    if (bm == null)
        return null;

    Bitmap result = bm;// ww w .  jav a2s .co m

    int ori = ExifInterface.ORIENTATION_NORMAL;

    try {
        ExifInterface ei = new ExifInterface(path);
        ori = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
    } catch (Exception e) {
        //simply fallback to normal orientation
        AQUtility.debug(e);
    }

    if (ori > 0) {

        Matrix matrix = getRotateMatrix(ori);
        result = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);

        AQUtility.debug("before", bm.getWidth() + ":" + bm.getHeight());
        AQUtility.debug("after", result.getWidth() + ":" + result.getHeight());

        if (bm != result) {
            bm.recycle();
        }
    }

    return result;
}