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:Main.java

public static Bitmap roundCornerFromFile(String filePath, int pixels) {
    try {//from   w  w  w. j a  va  2s  .c om
        Bitmap bitmap = BitmapFactory.decodeFile(filePath);
        if (bitmap == null)
            return null;
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        bitmap.recycle();
        bitmap = null;
        return output;
    } catch (OutOfMemoryError e) {
        return null;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.entertailion.android.slideshow.utils.Utils.java

/**
 * Determine if there is a high resolution icon available for the web site.
 * /*from w w w  .j av  a2s  .  c  o  m*/
 * @param context
 * @param url
 * @return
 */
public static final String getWebSiteIcon(Context context, String url) {
    String icon = null;
    if (url != null) {
        String data = Utils.getCachedData(context, url, true);
        if (data != null) {
            Document doc = Jsoup.parse(data);
            if (doc != null) {
                String href = null;
                Elements metas = doc.select("meta[itemprop=image]");
                if (metas.size() > 0) {
                    Element meta = metas.first();
                    href = meta.attr("abs:content");
                    // weird jsoup bug: abs doesn't always work
                    if (href == null || href.trim().length() == 0) {
                        href = url + meta.attr("content");
                    }
                }
                if (href == null || href.trim().length() == 0) {
                    // Find the Microsoft tile icon
                    metas = doc.select("meta[name=msapplication-TileImage]");
                    if (metas.size() > 0) {
                        Element meta = metas.first();
                        href = meta.attr("abs:content");
                        // weird jsoup bug: abs doesn't always work
                        if (href == null || href.trim().length() == 0) {
                            href = url + meta.attr("content");
                        }
                    }
                }
                if (href == null || href.trim().length() == 0) {
                    // Find the Apple touch icon
                    Elements links = doc.select("link[rel=apple-touch-icon]");
                    if (links.size() > 0) {
                        Element link = links.first();
                        href = link.attr("abs:href");
                        // weird jsoup bug: abs doesn't always work
                        if (href == null || href.trim().length() == 0) {
                            href = url + link.attr("href");
                        }
                    }
                }
                if (href == null || href.trim().length() == 0) {
                    // Find the Facebook open graph icon
                    metas = doc.select("meta[property=og:image]");
                    if (metas.size() > 0) {
                        Element link = metas.first();
                        href = link.attr("abs:content");
                        // weird jsoup bug: abs doesn't always work
                        if (href == null || href.trim().length() == 0) {
                            href = url + link.attr("content");
                        }
                    }
                }
                if (href != null && href.trim().length() > 0) {
                    try {
                        Bitmap bitmap = Utils.getBitmapFromURL(href);
                        if (bitmap != null) {
                            icon = "web_site_icon_" + Utils.clean(href) + ".png";
                            Utils.saveToFile(context, bitmap, bitmap.getWidth(), bitmap.getHeight(), icon);
                            bitmap.recycle();
                        }
                    } catch (Exception e) {
                        Log.d(LOG_TAG, "getWebSiteIcon", e);
                    }
                }
            }
        }
    }
    return icon;
}

From source file:Main.java

/**
 * Download the avatar image from the server.
 *
 * @param avatarUrl the URL pointing to the avatar image
 * @return a byte array with the raw JPEG avatar image
 *//*from w  ww. j a va2  s . c o  m*/
public static byte[] downloadAvatar(final String avatarUrl) {
    // If there is no avatar, we're done
    if (TextUtils.isEmpty(avatarUrl)) {
        return null;
    }

    try {
        Log.i(TAG, "Downloading avatar: " + avatarUrl);
        // Request the avatar image from the server, and create a bitmap
        // object from the stream we get back.
        URL url = new URL(avatarUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        try {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            final Bitmap avatar = BitmapFactory.decodeStream(connection.getInputStream(), null, options);

            // Take the image we received from the server, whatever format it
            // happens to be in, and convert it to a JPEG image. Note: we're
            // not resizing the avatar - we assume that the image we get from
            // the server is a reasonable size...
            Log.i(TAG, "Converting avatar to JPEG");
            ByteArrayOutputStream convertStream = new ByteArrayOutputStream(
                    avatar.getWidth() * avatar.getHeight() * 4);
            avatar.compress(Bitmap.CompressFormat.JPEG, 95, convertStream);
            convertStream.flush();
            convertStream.close();
            // On pre-Honeycomb systems, it's important to call recycle on bitmaps
            avatar.recycle();
            return convertStream.toByteArray();
        } finally {
            connection.disconnect();
        }
    } catch (MalformedURLException muex) {
        // A bad URL - nothing we can really do about it here...
        Log.e(TAG, "Malformed avatar URL: " + avatarUrl);
    } catch (IOException ioex) {
        // If we're unable to download the avatar, it's a bummer but not the
        // end of the world. We'll try to get it next time we sync.
        Log.e(TAG, "Failed to download user avatar: " + avatarUrl);
    }
    return null;
}

From source file:Main.java

public static Bitmap getRoundImage(Bitmap oriImg, boolean recycleOld) {

    Bitmap targetBitmap = null;/*from w ww  . j av a 2 s .  co m*/

    if (oriImg != null && !oriImg.isRecycled()) {
        int size = Math.min(oriImg.getWidth(), oriImg.getHeight());
        int targetWidth = size;
        int targetHeight = size;

        targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(targetBitmap);

        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        canvas.drawARGB(0, 0, 0, 0);
        canvas.drawCircle(targetWidth / 2f, targetHeight / 2f, targetWidth / 2f, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(oriImg, new Rect(0, 0, size, size), new Rect(0, 0, targetWidth, targetHeight), paint);

        if (recycleOld) {
            oriImg.recycle();
        }
    }
    return targetBitmap;
}

From source file:Main.java

public static Bitmap decodeBitmapFromFileToSize(String filePath, int reqWidth, int reqHeight,
        boolean maintainAspectRatio) {
    Bitmap original = BitmapFactory.decodeFile(filePath);
    if (original == null) {
        return null;
    }//  ww w.ja va  2 s  . c  o  m
    if (original.getWidth() == reqWidth || original.getHeight() == reqHeight) {
        return original;
    }

    if (maintainAspectRatio) {
        int oriWidth = original.getWidth(), oriHeight = original.getHeight();
        if (oriWidth >= oriHeight) {
            float aRatio = (float) oriHeight / (float) oriWidth;
            reqHeight = (int) (reqWidth * aRatio);
        } else if (oriHeight > oriWidth) {
            float aRatio = (float) oriWidth / (float) oriHeight;
            reqWidth = (int) (reqHeight * aRatio);
        }
    }

    Bitmap scaled = Bitmap.createScaledBitmap(original, reqWidth, reqHeight, false);
    if (scaled == null) {
        return original;
    }
    if (scaled != original) {
        original.recycle();
        original = null;
    }
    return scaled;
}

From source file:Main.java

public static Bitmap rotateAndMirror(Bitmap bitmap, int degree, boolean isMirror) throws OutOfMemoryError {

    if ((degree != 0 || isMirror) && bitmap != null) {
        Matrix m = new Matrix();
        m.setRotate(degree, (float) bitmap.getWidth() / 2, (float) bitmap.getHeight() / 2);

        if (isMirror) {
            m.postScale(-1, 1);/*from   ww w  .java2s.c  o  m*/
            degree = (degree + 360) % 360;
            if (degree == 0 || degree == 180) {
                m.postTranslate((float) bitmap.getWidth(), 0);
            } else if (degree == 90 || degree == 270) {
                m.postTranslate((float) bitmap.getHeight(), 0);
            } else {
                throw new IllegalArgumentException("Invalid degrees=" + degree);
            }
        }

        Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
        if (bitmap != bitmap2) {
            bitmap.recycle();
            System.gc();
            bitmap = bitmap2;
        }
    }
    return bitmap;
}

From source file:Main.java

public static Bitmap rotateBitmapInNeeded(String path, Bitmap srcBitmap) {
    if (TextUtils.isEmpty(path) || srcBitmap == null) {
        return null;
    }/*  ww w  . j a v  a  2s.  co  m*/

    ExifInterface localExifInterface;
    try {
        localExifInterface = new ExifInterface(path);
        int rotateInt = localExifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL);
        float rotate = getImageRotate(rotateInt);
        if (rotate != 0) {
            Matrix matrix = new Matrix();
            matrix.postRotate(rotate);
            Bitmap dstBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(),
                    matrix, false);
            if (dstBitmap == null) {
                return srcBitmap;
            } else {
                if (srcBitmap != null && !srcBitmap.isRecycled()) {
                    srcBitmap.recycle();
                }
                return dstBitmap;
            }
        } else {
            return srcBitmap;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return srcBitmap;
    }
}

From source file:com.talk.demo.util.NetworkUtilities.java

public static void downloadPhoto(final String photoName) {
    // If there is no photo, we're done
    if (TextUtils.isEmpty(photoName)) {
        return;/*from   www  .  j a v  a2  s.  c  o  m*/
    }

    try {
        Log.i(TAG, "Downloading photo: " + DOWNLOAD_PHOTO_URI);
        // Request the photo from the server, and create a bitmap
        // object from the stream we get back.
        URL url = new URL(DOWNLOAD_PHOTO_URI + photoName + "/");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        try {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            final Bitmap photo = BitmapFactory.decodeStream(connection.getInputStream(), null, options);

            Log.d(TAG, "file name : " + photoName);
            TalkUtil.createDirAndSaveFile(photo, photoName);
            // On pre-Honeycomb systems, it's important to call recycle on bitmaps
            photo.recycle();
        } finally {
            connection.disconnect();
        }
    } catch (MalformedURLException muex) {
        // A bad URL - nothing we can really do about it here...
        Log.e(TAG, "Malformed avatar URL: " + DOWNLOAD_PHOTO_URI);
    } catch (IOException ioex) {
        // If we're unable to download the avatar, it's a bummer but not the
        // end of the world. We'll try to get it next time we sync.
        Log.e(TAG, "Failed to download user avatar: " + DOWNLOAD_PHOTO_URI);
    }
}

From source file:Main.java

public static Bitmap getRoundAngleImage(Bitmap bitmap, int pixels, boolean recycleOld) {
    Bitmap output = null;/*  ww w .ja  v a2 s  .c  o  m*/
    if (bitmap != null && !bitmap.isRecycled()) {
        output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        canvas.drawARGB(0, 0, 0, 0);
        //            paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        if (recycleOld)
            bitmap.recycle();
        return output;
    }
    return output;
}

From source file:mobisocial.musubi.util.OGUtil.java

public static OGData getOrGuess(String url) {
    DefaultHttpClient hc = new DefaultHttpClient();
    HttpResponse res;//from  ww  w .  j  a  v a 2s.  c  o  m
    try {
        HttpGet hg = new HttpGet(url);
        res = hc.execute(hg);
    } catch (Exception e) {
        Log.e(TAG, "unable to fetch page to get og tags", e);
        return null;
    }
    String location = url;
    //TODO: if some kind of redirect magic happened, then
    //make the location match that

    OGData og = new OGData();
    HttpEntity he = res.getEntity();
    Header content_type = he.getContentType();
    //TODO: check the content directly if they forget the type header
    if (content_type == null || content_type.getValue() == null) {
        Log.e(TAG, "page missing content type ..abandoning: " + url);
        return null;
    }
    og.mMimeType = content_type.getValue();
    //just make a thumbnail if the shared item is an image
    if (og.mMimeType.startsWith("image/")) {
        Bitmap b;
        try {
            b = BitmapFactory.decodeStream(he.getContent());
        } catch (Exception e) {
            return null;
        }
        //TODO: scaling
        int w = b.getWidth();
        int h = b.getHeight();
        if (w > h) {
            h = h * 200 / w;
            w = 200;
        } else {
            w = w * 200 / h;
            h = 200;
        }

        Bitmap b2 = Bitmap.createScaledBitmap(b, w, h, true);
        b.recycle();
        b = b2;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        b.compress(CompressFormat.PNG, 100, baos);
        og.mImage = baos.toByteArray();
        b.recycle();
        return og;
    }
    //if its not html, we can't extract more details, the caller
    //should rely on what they already know.
    if (!og.mMimeType.startsWith("text/html") && !og.mMimeType.startsWith("application/xhtml")) {
        Log.e(TAG, "shared content is not a known type for meta data processing " + og.mMimeType);
        return og;
    }

    String html;
    try {
        html = IOUtils.toString(he.getContent());
    } catch (Exception e) {
        Log.e(TAG, "failed to read html content", e);
        return og;
    }

    Matcher m = sTitleRegex.matcher(html);
    if (m.find()) {
        og.mTitle = StringEscapeUtils.unescapeHtml4(m.group(1));

    }
    m = sMetaRegex.matcher(html);
    int offset = 0;
    String raw_description = null;
    while (m.find(offset)) {
        try {
            String meta_tag = m.group();
            Matcher mp = sPropertyOfMeta.matcher(meta_tag);
            if (!mp.find())
                continue;
            String type = mp.group(1);
            type = type.substring(1, type.length() - 1);
            Matcher md = sContentOfMeta.matcher(meta_tag);
            if (!md.find())
                continue;
            String data = md.group(1);
            //remove quotes
            data = data.substring(1, data.length() - 1);
            data = StringEscapeUtils.unescapeHtml4(data);
            if (type.equalsIgnoreCase("og:title")) {
                og.mTitle = data;
            } else if (type.equalsIgnoreCase("og:image")) {
                HttpResponse resi;
                try {
                    HttpGet hgi = new HttpGet(data);
                    resi = hc.execute(hgi);
                } catch (Exception e) {
                    Log.e(TAG, "unable to fetch og image url", e);
                    continue;
                }
                HttpEntity hei = resi.getEntity();
                if (!hei.getContentType().getValue().startsWith("image/")) {
                    Log.e(TAG, "image og tag points to non image data" + hei.getContentType().getValue());
                }
                try {
                    Bitmap b;
                    try {
                        b = BitmapFactory.decodeStream(hei.getContent());
                    } catch (Exception e) {
                        return null;
                    }
                    //TODO: scaling
                    int w = b.getWidth();
                    int h = b.getHeight();
                    if (w > h) {
                        h = h * Math.min(200, w) / w;
                        w = Math.min(200, w);
                    } else {
                        w = w * Math.min(200, h) / h;
                        h = Math.min(200, h);
                    }
                    Bitmap b2 = Bitmap.createScaledBitmap(b, w, h, true);
                    b.recycle();
                    b = b2;
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    b.compress(CompressFormat.PNG, 100, baos);
                    b.recycle();
                    og.mImage = baos.toByteArray();
                } catch (Exception e) {
                    Log.e(TAG, "failed to fetch image for og", e);
                    continue;
                }
            } else if (type.equalsIgnoreCase("description")) {
                raw_description = data;
            } else if (type.equalsIgnoreCase("og:description")) {
                og.mDescription = data;
            } else if (type.equalsIgnoreCase("og:url")) {
                og.mUrl = data;
            }
        } finally {
            offset = m.end();
        }
    }
    HashSet<String> already_fetched = new HashSet<String>();
    if (og.mImage == null) {
        int max_area = 0;
        m = sImageRegex.matcher(html);
        int img_offset = 0;
        while (m.find(img_offset)) {
            try {
                String img_tag = m.group();
                Matcher ms = sSrcOfImage.matcher(img_tag);
                if (!ms.find())
                    continue;
                String img_src = ms.group(1);
                img_src = img_src.substring(1, img_src.length() - 1);
                img_src = StringEscapeUtils.unescapeHtml4(img_src);
                //don't fetch an image twice (like little 1x1 images)
                if (already_fetched.contains(img_src))
                    continue;
                already_fetched.add(img_src);
                HttpResponse resi;
                try {
                    HttpGet hgi = new HttpGet(new URL(new URL(location), img_src).toString());
                    resi = hc.execute(hgi);
                } catch (Exception e) {
                    Log.e(TAG, "unable to fetch image url for biggest image search" + img_src, e);
                    continue;
                }
                HttpEntity hei = resi.getEntity();
                if (hei == null) {
                    Log.w(TAG, "image missing en ..trying entity response: " + url);
                    continue;
                }
                Header content_type_image = hei.getContentType();
                if (content_type_image == null || content_type_image.getValue() == null) {
                    Log.w(TAG, "image missing content type ..trying anyway: " + url);
                }
                if (!content_type_image.getValue().startsWith("image/")) {
                    Log.w(TAG, "image tag points to non image data " + hei.getContentType().getValue() + " "
                            + img_src);
                }
                try {
                    Bitmap b;
                    try {
                        b = BitmapFactory.decodeStream(hei.getContent());
                    } catch (Exception e) {
                        return null;
                    }
                    //TODO: scaling
                    int w = b.getWidth();
                    int h = b.getHeight();
                    if (w * h <= max_area) {
                        continue;
                    }
                    if (w < 32 || h < 32) {
                        //skip dinky crap
                        continue;
                    }
                    if (w > h) {
                        h = h * Math.min(200, w) / w;
                        w = Math.min(200, w);
                    } else {
                        w = w * Math.min(200, h) / h;
                        h = Math.min(200, h);
                    }
                    Bitmap b2 = Bitmap.createScaledBitmap(b, w, h, true);
                    b.recycle();
                    b = b2;
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    b.compress(CompressFormat.PNG, 100, baos);
                    og.mImage = baos.toByteArray();
                    b.recycle();
                    max_area = w * h;
                } catch (Exception e) {
                    Log.e(TAG, "failed to fetch image for og", e);
                    continue;
                }
            } finally {
                img_offset = m.end();
            }
        }

    }
    if (og.mDescription == null)
        og.mDescription = raw_description;
    return og;
}