Example usage for android.graphics Bitmap getByteCount

List of usage examples for android.graphics Bitmap getByteCount

Introduction

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

Prototype

public final int getByteCount() 

Source Link

Document

Returns the minimum number of bytes that can be used to store this bitmap's pixels.

Usage

From source file:com.dalaran.LDCache.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
@Override/*from w w w . ja v  a2s  .  c  o  m*/
public void putBitmap(String url, Bitmap bitmap) {

    if (bitmap.getHeight() >= 100 && bitmap.getWidth() >= 100) {

        bitmap = Bitmap.createScaledBitmap(bitmap, 100, 100, false);
    }

    Log.d("Disc cached:", url);
    final Cache.Entry entry = new Cache.Entry();

    try {
        ByteBuffer buffer = ByteBuffer.allocate(bitmap.getByteCount());
        bitmap.copyPixelsToBuffer(buffer);
        entry.data = buffer.array();
        put(url, entry);
        logicToPutBitmap(url, bitmap);
    } catch (Throwable e) {
        Log.w("Samsung 2.3.3", e.getMessage(), e);
    }
}

From source file:com.DGSD.Teexter.Utils.ContactPhotoManager.java

public ContactPhotoManagerImpl(Context context) {
    mContext = context;//  ww  w  .j ava  2 s.  co m

    final float cacheSizeAdjustment = 1.0f;
    final int bitmapCacheSize = (int) (cacheSizeAdjustment * BITMAP_CACHE_SIZE);
    mBitmapCache = new LruCache<Object, Bitmap>(bitmapCacheSize) {
        @Override
        protected int sizeOf(Object key, Bitmap value) {
            return value.getByteCount();
        }

        @Override
        protected void entryRemoved(boolean evicted, Object key, Bitmap oldValue, Bitmap newValue) {
        }
    };
    final int holderCacheSize = (int) (cacheSizeAdjustment * HOLDER_CACHE_SIZE);
    mBitmapHolderCache = new LruCache<Object, BitmapHolder>(holderCacheSize) {
        @Override
        protected int sizeOf(Object key, BitmapHolder value) {
            return value.bytes != null ? value.bytes.length : 0;
        }

        @Override
        protected void entryRemoved(boolean evicted, Object key, BitmapHolder oldValue, BitmapHolder newValue) {
        }
    };
    mBitmapHolderCacheRedZoneBytes = (int) (holderCacheSize * 0.75);
}

From source file:com.zhongsou.souyue.activity.SplashActivity.java

/**
 * ??/*  ww  w .java2 s . c o m*/
 */
private void allocMaxMemory() {
    if (mMemoryCache == null) {
        int maxMemory = (int) Runtime.getRuntime().maxMemory() / 1024;
        int cacheSize = maxMemory / 8;
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @SuppressLint("NewApi")
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount() / 1024;
            }
        };
    }
}

From source file:it.gmariotti.cardslib.library.view.component.CardThumbnailView.java

/**
 * Init view//from  ww w.j  a  v a2s  .c  om
 */
protected void initView() {

    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mInternalOuterView = inflater.inflate(card_thumbnail_layout_resourceID, this, true);

    //Get ImageVIew
    mImageView = (ImageView) findViewById(R.id.card_thumbnail_image);

    // Get max available VM memory, exceeding this amount will throw an
    // OutOfMemory exception. Stored in kilobytes as LruCache takes an
    // int in its constructor.
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

    // Use 1/8th of the available memory for this memory cache.
    final int cacheSize = maxMemory / 8;

    mMemoryCache = CacheUtil.getMemoryCache();
    if (mMemoryCache == null) {
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {

            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                // The cache size will be measured in kilobytes rather than
                // number of items.
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR1) {
                    return bitmap.getByteCount() / 1024;
                } else {
                    return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
                }
            }
        };
        CacheUtil.putMemoryCache(mMemoryCache);
    }
}

From source file:com.luke.lukef.lukeapp.fragments.NewSubmissionFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;/*from  w ww  . j  av a 2  s .  co  m*/
        Bitmap imageBitmap = BitmapFactory.decodeFile(this.photoPath, options);
        if (imageBitmap != null) {
            try {
                Log.e(TAG, "onActivityResult: photo file before write" + this.photoFile.length());
                FileOutputStream fo = new FileOutputStream(this.photoFile);
                imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fo);
                Log.e(TAG, "onActivityResult: photo file after write" + this.photoFile.length());
            } catch (FileNotFoundException e) {
                Log.e(TAG, "onActivityResult: ", e);
            }

            imageBitmap = BitmapFactory.decodeFile(photoPath, options);

            if (imageBitmap != null)
                Log.e(TAG, "onActivityResult: photo exists, size : " + imageBitmap.getByteCount());
            photoThumbnail.setImageBitmap(imageBitmap);
            this.currentPhoto = imageBitmap;
        } else {
            getMainActivity().makeToast("Error taking picture");
        }
    }
}

From source file:com.vishwa.pinit.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    mFrameLayout = new FrameLayout(this);

    if (getResources().getBoolean(R.bool.portrait_only)) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }//from   w w w .  ja va 2 s  .  c o m

    setContentView(mFrameLayout);

    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflater.inflate(R.layout.activity_main, mFrameLayout);

    inflater.inflate(R.layout.splash_screen, mFrameLayout);
    mHandler = new Handler();
    final Runnable runnable = new Runnable() {

        @Override
        public void run() {
            Animation fadeOutAnimation = AnimationUtils.loadAnimation(getApplicationContext(),
                    android.R.anim.fade_out);
            fadeOutAnimation.setAnimationListener(new AnimationListener() {

                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    mFrameLayout.removeViewAt(1);
                    if (PinItUtils.isUsersFirstLogin(mCurrentUsername, getApplicationContext())) {
                        if (!DEBUG) {
                            handleUsersFirstTime();
                        }
                    }
                }
            });
            mFrameLayout.getChildAt(1).startAnimation(fadeOutAnimation);
        }

    };
    mHandler.postDelayed(runnable, 2300);

    mCurrentUsername = ParseUser.getCurrentUser().getUsername();

    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

    final int cacheSize = maxMemory / 10;

    RetainFragment mRetainFragment = RetainFragment.findOrCreateRetainFragment(getSupportFragmentManager());
    mMemoryCache = mRetainFragment.mRetainedCache;
    if (mMemoryCache == null) {
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return bitmap.getByteCount() / 1024;
            }
        };
        mRetainFragment.mRetainedCache = mMemoryCache;
    }

    mAllNotesButton = (Button) findViewById(R.id.main_all_notes_button);
    mYourNotesButton = (Button) findViewById(R.id.main_your_notes_button);

    setProgressBarIndeterminateVisibility(false);

    mAllNotesButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            LatLngBounds mapBounds = mMap.getProjection().getVisibleRegion().latLngBounds;
            LatLng southwest = mapBounds.southwest;
            LatLng northeast = mapBounds.northeast;

            mMapViewMode = MapViewMode.ALL_NOTES;

            for (Marker marker : mMarkerList) {
                marker.remove();
            }

            mMarkerList.clear();
            mNoteStore.clear();
            mReverseNoteStore.clear();

            LatLngTuple tuple = new LatLngTuple(southwest, northeast);
            LoadNotesTask currentUserNotesTask = new LoadNotesTask(tuple, false);
            currentUserNotesTask.execute();
            setProgressBarIndeterminateVisibility(true);
        }
    });

    mYourNotesButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            LatLngBounds mapBounds = mMap.getProjection().getVisibleRegion().latLngBounds;
            LatLng southwest = mapBounds.southwest;
            LatLng northeast = mapBounds.northeast;

            for (Marker marker : mMarkerList) {
                marker.remove();
            }

            mMarkerList.clear();
            mNoteStore.clear();
            mReverseNoteStore.clear();

            mMapViewMode = MapViewMode.YOUR_NOTES;
            LatLngTuple tuple = new LatLngTuple(southwest, northeast);
            LoadNotesTask currentUserNotesTask = new LoadNotesTask(tuple, true);
            currentUserNotesTask.execute();
            setProgressBarIndeterminateVisibility(true);
        }
    });

    try {
        MapsInitializer.initialize(this);
        if (!PinItUtils.isOnline(getApplicationContext())) {
            PinItUtils.createAlert("Internet connection not found.",
                    "Connect to the Internet and press the refresh button at the top", this);
            mHasInternet = false;
        } else {
            mHasInternet = true;
            loadMapWhenOnline();
        }
    } catch (GooglePlayServicesNotAvailableException e) {
        PinItUtils.createAlert("We're sorry",
                "It seems that your phone doesn't have Google Play"
                        + "services installed, or is missing the maps application. Please download both of"
                        + "these and then try running this application",
                MainActivity.this);
    }

}

From source file:com.silentcircle.contacts.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  w w  . j av a 2 s .  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);

        // 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) {
            int bCount = (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1)
                    ? bitmap.getRowBytes() * bitmap.getHeight()
                    : bitmap.getByteCount();
            Log.d(TAG, "inflateBitmap " + btk(bytes.length) + " -> " + bitmap.getWidth() + "x"
                    + bitmap.getHeight() + ", " + btk(bCount));
        }
    } catch (OutOfMemoryError e) {
        // Do nothing - the photo will appear to be missing
    }
}

From source file:com.silentcircle.contacts.ContactPhotoManager.java

public ContactPhotoManagerImpl(Context context) {
    mContext = context;/*w w w  .  j a v a 2  s  .  c  o  m*/

    final float cacheSizeAdjustment = (MemoryUtils.getTotalMemorySize() >= LARGE_RAM_THRESHOLD) ? 1.0f : 0.5f;
    final int bitmapCacheSize = (int) (cacheSizeAdjustment * BITMAP_CACHE_SIZE);
    mBitmapCache = new LruCache<Object, Bitmap>(bitmapCacheSize) {
        @Override
        @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
        protected int sizeOf(Object key, Bitmap data) {
            return (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1)
                    ? (data.getRowBytes() * data.getHeight())
                    : data.getByteCount();
        }

        @Override
        protected void entryRemoved(boolean evicted, Object key, Bitmap oldValue, Bitmap newValue) {
            if (DEBUG)
                dumpStats();
        }
    };
    final int holderCacheSize = (int) (cacheSizeAdjustment * HOLDER_CACHE_SIZE);
    mBitmapHolderCache = new LruCache<Object, BitmapHolder>(holderCacheSize) {
        @Override
        protected int sizeOf(Object key, BitmapHolder value) {
            return value.bytes != null ? value.bytes.length : 0;
        }

        @Override
        protected void entryRemoved(boolean evicted, Object key, BitmapHolder oldValue, BitmapHolder newValue) {
            if (DEBUG)
                dumpStats();
        }
    };
    mBitmapHolderCacheRedZoneBytes = (int) (holderCacheSize * 0.75);
    Log.i(TAG, "Cache adj: " + cacheSizeAdjustment);
    if (DEBUG) {
        Log.d(TAG, "Cache size: " + btk(mBitmapHolderCache.maxSize()) + " + " + btk(mBitmapCache.maxSize()));
    }
}

From source file:cx.ring.service.LocalService.java

@Override
public void onCreate() {
    Log.e(TAG, "onCreate");
    super.onCreate();

    mediaManager = new MediaManager(this);

    notificationManager = NotificationManagerCompat.from(this);

    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    final int cacheSize = maxMemory / 8;
    mMemoryCache = new LruCache<Long, Bitmap>(cacheSize) {
        @Override//  ww  w  . java2s .com
        protected int sizeOf(Long key, Bitmap bitmap) {
            return bitmap.getByteCount() / 1024;
        }
    };

    historyManager = new HistoryManager(this);
    Intent intent = new Intent(this, DRingService.class);
    startService(intent);
    bindService(intent, mConnection, BIND_AUTO_CREATE | BIND_IMPORTANT | BIND_ABOVE_CLIENT);

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    isWifiConn = ni != null && ni.isConnected();
    ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    isMobileConn = ni != null && ni.isConnected();

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    canUseContacts = sharedPreferences.getBoolean(SettingsFragment.KEY_PREF_CONTACTS, true);
    canUseMobile = sharedPreferences.getBoolean(SettingsFragment.KEY_PREF_MOBILE, true);
    sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}

From source file:com.silentcircle.contacts.ContactPhotoManager.java

/**
 * Dump cache stats on logcat./*from  ww w .j  a va  2s .  co  m*/
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
private void dumpStats() {
    if (!DEBUG)
        return;
    {
        int numHolders = 0;
        int rawBytes = 0;
        int bitmapBytes = 0;
        int numBitmaps = 0;
        for (BitmapHolder h : mBitmapHolderCache.snapshot().values()) {
            numHolders++;
            if (h.bytes != null) {
                rawBytes += h.bytes.length;
            }
            Bitmap b = h.bitmapRef != null ? h.bitmapRef.get() : null;
            if (b != null) {
                int bCount = (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1)
                        ? b.getRowBytes() * b.getHeight()
                        : b.getByteCount();
                numBitmaps++;
                bitmapBytes += bCount;
            }
        }
        Log.d(TAG,
                "L1: " + btk(rawBytes) + " + " + btk(bitmapBytes) + " = " + btk(rawBytes + bitmapBytes) + ", "
                        + numHolders + " holders, " + numBitmaps + " bitmaps, avg: "
                        + btk(safeDiv(rawBytes, numHolders)) + "," + btk(safeDiv(bitmapBytes, numBitmaps)));
        Log.d(TAG, "L1 Stats: " + mBitmapHolderCache.toString() + ", overwrite: fresh="
                + mFreshCacheOverwrite.get() + " stale=" + mStaleCacheOverwrite.get());
    }

    {
        int numBitmaps = 0;
        int bitmapBytes = 0;
        for (Bitmap b : mBitmapCache.snapshot().values()) {
            numBitmaps++;
            int bCount = (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1)
                    ? b.getRowBytes() * b.getHeight()
                    : b.getByteCount();
            bitmapBytes += bCount;
        }
        Log.d(TAG, "L2: " + btk(bitmapBytes) + ", " + numBitmaps + " bitmaps" + ", avg: "
                + btk(safeDiv(bitmapBytes, numBitmaps)));
        // We don't get from L2 cache, so L2 stats is meaningless.
    }
}