List of usage examples for android.graphics Bitmap getRowBytes
public final int getRowBytes()
From source file:it.angelic.soulissclient.fragments.TagDetailFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.recycler_view_frag, container, false); rootView.setTag(TAG);/*from w ww . j av a2s . co m*/ Log.i(Constants.TAG, "onCreateView with size of data:" + collectedTagTypicals.size()); appBarLayout = (AppBarLayout) getActivity().findViewById(R.id.appBar_layout); swipeLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeRefreshContainer); swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new Thread(new Runnable() { @Override public void run() { Looper.prepare(); if (collectedTag != null) { UDPHelper.stateRequest(opzioni, 1, collectedTag.getAssignedTypicals().get(0).getNodeId()); Log.d(Constants.TAG, "stateRequest for node:" + collectedTag.getAssignedTypicals().get(0).getNodeId()); } if (!opzioni.isSoulissReachable()) { getActivity().runOnUiThread(new Runnable() { public void run() { Toast.makeText(getActivity(), getString(R.string.status_souliss_notreachable), Toast.LENGTH_SHORT).show(); swipeLayout.setRefreshing(false); } }); } } }).start(); } }); swipeLayout.setColorSchemeResources(R.color.std_blue, R.color.std_blue_shadow); // BEGIN_INCLUDE(initializeRecyclerView) mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView); swipeLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeRefreshContainer); // LinearLayout tagContainer = (LinearLayout) rootView.findViewById(R.id.tagContainer); //mLayoutManager = new LinearLayoutManager(getActivity()); if (savedInstanceState != null) { // Restore saved layout manager type. mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState.getSerializable(KEY_LAYOUT_MANAGER); } mCurrentLayoutManagerType = getResources() .getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? LayoutManagerType.GRID_LAYOUT_MANAGER : LayoutManagerType.LINEAR_LAYOUT_MANAGER; setRecyclerViewLayoutManager(mCurrentLayoutManagerType); parallaxExtAdapter = new ParallaxExenderAdapter(opzioni, (TagDetailActivity) getActivity(), collectedTagTypicals, tagId); //HeaderLayoutManagerFixed layoutManagerFixed = new HeaderLayoutManagerFixed(getActivity()); //HEADER // View header = getLayoutInflater(null).inflate(R.layout.head_tagdetail, tagContainer, false); // layoutManagerFixed.setHeaderIncrementFixer(header); mLogoIcon = (ImageView) getActivity().findViewById(R.id.imageTagIcon); if (collectedTag.getIconResourceId() != 0) mLogoIcon.setImageResource(collectedTag.getIconResourceId()); mLogoImg = (ImageView) getActivity().findViewById(R.id.photo); bro = (TextView) getActivity().findViewById(R.id.tagTextView); collapseToolbar = (CollapsingToolbarLayout) getActivity().findViewById(R.id.Collapselayout); fab = (FloatingActionButton) getActivity().findViewById(R.id.fabTag); //EDIT TAG fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder alert = AlertDialogHelper.renameSoulissObjectDialog(getActivity(), bro, null, datasource, collectedTag); alert.show(); } }); fab.hide(false); fab.postDelayed(new Runnable() { @Override public void run() { fab.show(true); } }, 500); swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new Thread(new Runnable() { @Override public void run() { Looper.prepare(); for (SoulissTypical typ : collectedTagTypicals) { UDPHelper.stateRequest(opzioni, 4, typ.getSlot()); } //Avvisa solo if (!opzioni.isSoulissReachable()) { getActivity().runOnUiThread(new Runnable() { public void run() { Toast.makeText(getActivity(), getString(R.string.status_souliss_notreachable), Toast.LENGTH_SHORT).show(); swipeLayout.setRefreshing(false); } }); } } }).start(); } }); swipeLayout.setColorSchemeResources(R.color.std_blue, R.color.std_blue_shadow); if (bro != null && collectedTag != null) { // bro.setText(collectedTag.getNiceName()); collapseToolbar.setTitle(collectedTag.getNiceName()); } if (collectedTag != null && collectedTag.getImagePath() != null) { File picture = new File(getRealPathFromURI(Uri.parse(collectedTag.getImagePath()))); // File picture = new File(Uri.parse(collectedTag.getImagePath()).getPath()); if (picture.exists()) { //ImageView imageView = (ImageView)findViewById(R.id.imageView); BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 2; Bitmap myBitmap = BitmapFactory.decodeFile(picture.getAbsolutePath(), options); if (myBitmap.getHeight() > mRecyclerView.getWidth()) myBitmap = Bitmap.createScaledBitmap(myBitmap, myBitmap.getWidth() / 2, myBitmap.getHeight() / 2, true); Log.i(Constants.TAG, "bitmap size " + myBitmap.getRowBytes()); mLogoImg.setImageBitmap(myBitmap); } try { mLogoImg.setImageURI(Uri.parse(collectedTag.getImagePath())); } catch (Exception e) { Log.d(TAG, "can't set logo", e); } } //parallaxExtAdapter.setShouldClipView(true); // parallaxExtAdapter.setParallaxHeader(header, mRecyclerView); registerForContextMenu(mRecyclerView); return rootView; }
From source file:com.serenegiant.testmediastore.MediaStorePhotoAdapter.java
/** * create thumbnail cache// ww w.j a v a 2 s .c om */ @SuppressLint("NewApi") private final void createBitmapCache(boolean clear) { if (clear && (sThumbnailCache != null)) { sThumbnailCache.evictAll(); System.gc(); } if (sThumbnailCache == null) { // use 1/CACHE_RATE of available memory as memory cache final int cacheSize = 1024 * 1024 * mMemClass / CACHE_RATE; // [MB] => [bytes] sThumbnailCache = new LruCache<Long, Bitmap>(cacheSize) { @Override protected int sizeOf(Long key, Bitmap bitmap) { // control memory usage instead of bitmap counts return bitmap.getRowBytes() * bitmap.getHeight(); // [bytes] } }; } if (Build.VERSION.SDK_INT >= 9) { EXECUTER.allowCoreThreadTimeOut(true); // this makes core threads can terminate } // in many case, calling createBitmapCache method means start the new query // and need to prepare to run asynchronus tasks EXECUTER.prestartAllCoreThreads(); }
From source file:it.gmariotti.cardslib.library.view.component.CardThumbnailView.java
/** * Init view/*w ww .j a v a 2s . c o m*/ */ 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.example.psumaps.MapView.java
public static Bitmap convertToMutable(Bitmap imgIn) { try {//from w w w .j a v a 2 s.c o m // this is the file going to use temporally to save the bytes. // This file will not be a image, it will store the raw image data. File file = new File(Environment.getExternalStorageDirectory() + File.separator + "temp.tmp"); // Open an RandomAccessFile // Make sure you have added uses-permission // android:name="android.permission.WRITE_EXTERNAL_STORAGE" // into AndroidManifest.xml file RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); // get the width and height of the source bitmap. int width = imgIn.getWidth(); int height = imgIn.getHeight(); Bitmap.Config type = imgIn.getConfig(); // Copy the byte to the file // Assume source bitmap loaded using options.inPreferredConfig = // Config.ARGB_8888; FileChannel channel = randomAccessFile.getChannel(); MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE, 0, imgIn.getRowBytes() * height); imgIn.copyPixelsToBuffer(map); // recycle the source bitmap, this will be no longer used. imgIn.recycle(); System.gc();// try to force the bytes from the imgIn to be released // Create a new bitmap to load the bitmap again. Probably the memory // will be available. imgIn = Bitmap.createBitmap(width, height, type); map.position(0); // load it back from temporary imgIn.copyPixelsFromBuffer(map); // close the temporary file and channel , then delete that also channel.close(); randomAccessFile.close(); // delete the temp file file.delete(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return imgIn; }
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 ww . j ava 2 s.co m 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;/*from ww w .j a v a 2 s . c om*/ 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:com.silentcircle.contacts.ContactPhotoManager.java
/** * Dump cache stats on logcat.//from ww w . j av a 2 s . c o 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. } }
From source file:com.spoiledmilk.ibikecph.util.Util.java
public static Bitmap bmpDecodeFile(File f, int width_limit, int height_limit, long max_size, boolean max_dimensions) { if (f == null) { return null; }/*from ww w .j a va2 s .c om*/ LOG.d("bmpDecodeFile(" + f.getAbsolutePath() + "," + width_limit + "," + height_limit + "," + max_size + "," + max_dimensions + ")"); Bitmap bmp = null; boolean shouldReturn = false; FileInputStream fin = null; int orientation = ExifInterface.ORIENTATION_NORMAL; try { // Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; fin = new FileInputStream(f); BitmapFactory.decodeStream(fin, null, o); try { fin.close(); fin = null; } catch (IOException e) { } // Find the correct scale value. It should be the power of 2. int scale = 1; if (width_limit != -1 && height_limit != -1) { if (max_dimensions) { while (o.outWidth / scale > width_limit || o.outHeight / scale > height_limit) scale *= 2; } else { while (o.outWidth / scale / 2 >= width_limit && o.outHeight / scale / 2 >= height_limit) scale *= 2; } } else if (max_size != -1) while ((o.outWidth * o.outHeight) / (scale * scale) > max_size) scale *= 2; // Decode with inSampleSize o = null; if (scale > 1) { o = new BitmapFactory.Options(); o.inSampleSize = scale; } fin = new FileInputStream(f); try { bmp = BitmapFactory.decodeStream(fin, null, o); } catch (OutOfMemoryError e) { // Try to recover from out of memory error - but keep in mind // that behavior after this error is // undefined, // for example more out of memory errors might appear in catch // block. if (bmp != null) bmp.recycle(); bmp = null; System.gc(); LOG.e("Util.bmpDecodeFile() OutOfMemoryError in decodeStream()! Trying to recover..."); } if (bmp != null) { LOG.d("resulting bitmap width : " + bmp.getWidth() + " height : " + bmp.getHeight() + " size : " + (bmp.getRowBytes() * bmp.getHeight())); ExifInterface exif = new ExifInterface(f.getPath()); orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); } } catch (FileNotFoundException e) { shouldReturn = true; } catch (IOException e) { shouldReturn = true; // bitmap is still valid here, just can't be // rotated } finally { if (fin != null) try { fin.close(); } catch (IOException e) { } } if (shouldReturn || bmp == null) return bmp; float rotate = 0; switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: rotate = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: rotate = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: rotate = 270; break; } if (rotate > 0) { Matrix matrix = new Matrix(); matrix.postRotate(rotate); Bitmap bmpRot = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true); matrix = null; bmp.recycle(); bmp = null; // System.gc(); return bmpRot; } return bmp; }
From source file:com.silentcircle.contacts.ContactPhotoManager.java
/** * Checks if the photo is present in cache. If so, sets the photo on the view. * * @return false if the photo needs to be (re)loaded from the provider. *///from ww w.j av a 2 s . co m private boolean loadCachedPhoto(ImageView view, Request request, boolean fadeIn) { BitmapHolder holder = mBitmapHolderCache.get(request.getKey()); if (holder == null) { // The bitmap has not been loaded ==> show default avatar request.applyDefaultImage(view); return false; } if (holder.bytes == null) { request.applyDefaultImage(view); return holder.fresh; } Bitmap cachedBitmap = holder.bitmapRef == null ? null : holder.bitmapRef.get(); if (cachedBitmap == null) { if (holder.bytes.length < 8 * 1024) { // Small thumbnails are usually quick to inflate. Let's do that on the UI thread inflateBitmap(holder, request.getRequestedExtent()); cachedBitmap = holder.bitmap; if (cachedBitmap == null) return false; } else { // This is bigger data. Let's send that back to the Loader so that we can // inflate this in the background request.applyDefaultImage(view); return false; } } final Drawable previousDrawable = view.getDrawable(); if (fadeIn && previousDrawable != null) { final Drawable[] layers = new Drawable[2]; // Prevent cascade of TransitionDrawables. if (previousDrawable instanceof TransitionDrawable) { final TransitionDrawable previousTransitionDrawable = (TransitionDrawable) previousDrawable; layers[0] = previousTransitionDrawable .getDrawable(previousTransitionDrawable.getNumberOfLayers() - 1); } else { layers[0] = previousDrawable; } layers[1] = new BitmapDrawable(mContext.getResources(), cachedBitmap); TransitionDrawable drawable = new TransitionDrawable(layers); view.setImageDrawable(drawable); drawable.startTransition(FADE_TRANSITION_DURATION); } else { view.setImageBitmap(cachedBitmap); } // Put the bitmap in the LRU cache. But only do this for images that are small enough // (we require that at least six of those can be cached at the same time) int byteCount = (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1) ? cachedBitmap.getRowBytes() * cachedBitmap.getHeight() : cachedBitmap.getByteCount(); if (byteCount < mBitmapCache.maxSize() / 6) { mBitmapCache.put(request.getKey(), cachedBitmap); } holder.bitmap = null; // Soften the reference return holder.fresh; }