List of usage examples for android.graphics Bitmap getByteCount
public final int getByteCount()
From source file:com.onedollar.image.ImageCache.java
/** * @param candidate//from w w w .j a va2 s . c o m * - Bitmap to check * @param targetOptions * - Options that have the out* value populated * @return true if <code>candidate</code> can be used for inBitmap re-use * with <code>targetOptions</code> */ @TargetApi(VERSION_CODES.JELLY_BEAN) private static boolean canUseForInBitmap(Bitmap candidate, BitmapFactory.Options targetOptions) { // BEGIN_INCLUDE(can_use_for_inbitmap) if (!Utils.hasJellyBean()) { // On earlier versions, the dimensions must match exactly and the // inSampleSize must be 1 return candidate.getWidth() == targetOptions.outWidth && candidate.getHeight() == targetOptions.outHeight && targetOptions.inSampleSize == 1; } // From Android 4.4 (KitKat) onward we can re-use if the byte size of // the new bitmap // is smaller than the reusable bitmap candidate allocation byte count. int width = targetOptions.outWidth / targetOptions.inSampleSize; int height = targetOptions.outHeight / targetOptions.inSampleSize; int byteCount = width * height * getBytesPerPixel(candidate.getConfig()); return byteCount <= candidate.getByteCount(); // END_INCLUDE(can_use_for_inbitmap) }
From source file:com.jasper.image.imagemanager.imagehelper.imageEngine.ImageCache.java
/** * @param candidate - Bitmap to check * @param targetOptions - Options that have the out* value populated * @return true if <code>candidate</code> can be used for inBitmap re-use * with <code>targetOptions</code> *//*from w w w.jav a2s . c o m*/ @TargetApi(19) private static boolean canUseForInBitmap(Bitmap candidate, BitmapFactory.Options targetOptions) { // BEGIN_INCLUDE(can_use_for_inbitmap) if (!VersionUtils.hasKitKat()) { // On earlier versions, the dimensions must match exactly and the // inSampleSize must be 1 return candidate.getWidth() == targetOptions.outWidth && candidate.getHeight() == targetOptions.outHeight && targetOptions.inSampleSize == 1; } // From Android 4.4 (KitKat) onward we can re-use if the byte size of // the new bitmap // is smaller than the reusable bitmap candidate allocation byte count. else { int width = targetOptions.outWidth / targetOptions.inSampleSize; int height = targetOptions.outHeight / targetOptions.inSampleSize; int byteCount = width * height * getBytesPerPixel(candidate.getConfig()); // return byteCount <= candidate.getAllocationByteCount(); return byteCount <= candidate.getByteCount(); } // END_INCLUDE(can_use_for_inbitmap) }
From source file:io.jawg.osmcontributor.ui.utils.BitmapHandler.java
@Inject public BitmapHandler(Application osmTemplateApplication) { context = osmTemplateApplication.getApplicationContext(); final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // Use 1/5th of the available memory for this memory cache. final int cacheSize = maxMemory / 5; cache = new LruCache<String, Bitmap>(cacheSize) { @Override/* w w w. ja va 2 s. c o m*/ protected int sizeOf(String key, Bitmap bitmap) { // The cache size will be measured in kilobytes rather than items count return bitmap.getByteCount() / 1024; } }; icons.put("administrative", R.drawable.administrative); icons.put("animal_shelter", R.drawable.pet2); icons.put("antique", R.drawable.archaeological); icons.put("gallery", R.drawable.art_gallery2); icons.put("boat_sharing", R.drawable.sailing); icons.put("books", R.drawable.library); icons.put("boutique", R.drawable.convenience); icons.put("brothel", R.drawable.hotel2); icons.put("bureau_de_change", R.drawable.currency_exchange); icons.put("camp_site", R.drawable.camping); icons.put("car_wash", R.drawable.ford); icons.put("car_sharing", R.drawable.car_share); icons.put("clinic", R.drawable.doctors2); icons.put("arts_centre", R.drawable.art_gallery2); icons.put("dry_cleaning", R.drawable.laundrette); icons.put("archaeological_site", R.drawable.archaeological2); icons.put("farm", R.drawable.marketplace); icons.put("variety_store", R.drawable.convenience); icons.put("food_court", R.drawable.marketplace); icons.put("fort", R.drawable.castle2); icons.put("general", R.drawable.department_store); icons.put("hardware", R.drawable.mine); icons.put("doityourself", R.drawable.diy); icons.put("organic", R.drawable.greengrocer); icons.put("laundry", R.drawable.laundrette); icons.put("kindergarten", R.drawable.nursery3); icons.put("manor", R.drawable.house); icons.put("alpine_hut", R.drawable.alpinehut); icons.put("wilderness_hut", R.drawable.alpinehut); icons.put("ship", R.drawable.sailing); icons.put("music_venue", R.drawable.music); icons.put("music_venue", R.drawable.music); icons.put("nursing_home", R.drawable.hotel2); icons.put("optician", R.drawable.opticians); icons.put("viewpoint", R.drawable.photo); icons.put("crossing", R.drawable.zebra_crossing); icons.put("guest_house", R.drawable.bed_and_breakfast2); icons.put("photo_booth", R.drawable.photo); icons.put("picnic_site", R.drawable.picnic); icons.put("services", R.drawable.picnic); icons.put("public_bookcase", R.drawable.library); icons.put("register_office", R.drawable.administrative); icons.put("mini_roundabout", R.drawable.roundabout_anticlockwise); icons.put("ruins", R.drawable.ruin); icons.put("caravan_site", R.drawable.caravan_park); icons.put("tailor", R.drawable.clothes); icons.put("taxi", R.drawable.taxi_rank); icons.put("tomb", R.drawable.memorial); icons.put("travel_agency", R.drawable.aerodrome); icons.put("video", R.drawable.video_rental); icons.put("waste_basket", R.drawable.waste_bin); icons.put("waste_basket", R.drawable.waste_bin); icons.put("artwork", R.drawable.art_gallery); icons.put("aerodrome", R.drawable.aerodrome); icons.put("aircraft", R.drawable.aerodrome); icons.put("alcohol", R.drawable.bar); icons.put("atm", R.drawable.atm); icons.put("attraction", R.drawable.attraction); icons.put("bank", R.drawable.bank); icons.put("bar", R.drawable.bar); icons.put("bus_stop", R.drawable.bus_stop); icons.put("bicycle_parking", R.drawable.bicycle_parking); icons.put("bicycle_rental", R.drawable.bicycle_rental); icons.put("biergarten", R.drawable.biergarten); icons.put("cafe", R.drawable.cafe); icons.put("car_rental", R.drawable.car_rental); icons.put("church", R.drawable.place_of_worship); icons.put("cinema", R.drawable.cinema); icons.put("city", R.drawable.town); icons.put("commercial", R.drawable.mall); icons.put("courthouse", R.drawable.courthouse); icons.put("dentist", R.drawable.dentist); icons.put("doctors", R.drawable.doctors); icons.put("drinking_water", R.drawable.drinking_water); icons.put("embassy", R.drawable.embassy); icons.put("entrance", R.drawable.entrance); icons.put("fast_food", R.drawable.fast_food); icons.put("fire_station", R.drawable.fire_station); icons.put("fuel", R.drawable.fuel); icons.put("hamlet", R.drawable.town); icons.put("hospital", R.drawable.hospital); icons.put("hotel", R.drawable.hotel); icons.put("house", R.drawable.house); icons.put("housenumber", R.drawable.house); icons.put("hunting_stand", R.drawable.hunting_stand); icons.put("locality", R.drawable.town); icons.put("mall", R.drawable.mall); icons.put("nightclub", R.drawable.nightclub); icons.put("neighbourhood", R.drawable.house); icons.put("parking", R.drawable.parking); icons.put("pharmacy", R.drawable.pharmacy); icons.put("place_of_worship", R.drawable.place_of_worship); icons.put("police", R.drawable.police); icons.put("political", R.drawable.administrative); icons.put("primary", R.drawable.street); icons.put("prison", R.drawable.prison); icons.put("pub", R.drawable.pub); icons.put("recycling", R.drawable.recycling); icons.put("religious_administrative", R.drawable.place_of_worship); icons.put("residential", R.drawable.house); icons.put("restaurant", R.drawable.restaurant); icons.put("retail", R.drawable.mall); icons.put("road", R.drawable.street); icons.put("secondary", R.drawable.street); icons.put("stadium", R.drawable.stadium); icons.put("station", R.drawable.bus_stop); icons.put("street", R.drawable.street); icons.put("suburb", R.drawable.town); icons.put("subway_entrance", R.drawable.bus_stop); icons.put("platform", R.drawable.bus_stop); icons.put("supermarket", R.drawable.mall); icons.put("terminal", R.drawable.aerodrome); icons.put("tertiary", R.drawable.street); icons.put("theatre", R.drawable.theatre); icons.put("toilets", R.drawable.toilets); icons.put("town", R.drawable.town); icons.put("townhall", R.drawable.townhall); icons.put("track", R.drawable.street); icons.put("village", R.drawable.town); icons.put("phone", R.drawable.sos); }
From source file:com.layer.atlas.Atlas.java
/** * @param imageFile - to create a preview of * @param layerClient - required to create {@link MessagePart} * @param tempDir - required to store preview file until it is picked by LayerClient * @return MessagePart[] {previewBytes, json_with_dimensions} or null if preview cannot be built *//*from ww w .ja v a 2 s . com*/ public static MessagePart[] buildPreviewAndSize(final File imageFile, final LayerClient layerClient, File tempDir) throws IOException { if (imageFile == null) throw new IllegalArgumentException("imageFile cannot be null"); if (layerClient == null) throw new IllegalArgumentException("layerClient cannot be null"); if (tempDir == null) throw new IllegalArgumentException("tempDir cannot be null"); if (!tempDir.exists()) throw new IllegalArgumentException("tempDir doesn't exist"); if (!tempDir.isDirectory()) throw new IllegalArgumentException("tempDir must be a directory"); // prepare preview BitmapFactory.Options optOriginal = new BitmapFactory.Options(); optOriginal.inJustDecodeBounds = true; //BitmapFactory.decodeFile(photoFile.getAbsolutePath(), optOriginal); BitmapFactory.decodeStream(new FileInputStream(imageFile), null, optOriginal); if (debug) Log.w(TAG, "buildPreviewAndSize() original: " + optOriginal.outWidth + "x" + optOriginal.outHeight); int previewWidthMax = 512; int previewHeightMax = 512; int previewWidth; int previewHeight; int sampleSize; if (optOriginal.outWidth > optOriginal.outHeight) { sampleSize = optOriginal.outWidth / previewWidthMax; previewWidth = previewWidthMax; previewHeight = (int) (1.0 * previewWidth * optOriginal.outHeight / optOriginal.outWidth); if (debug) Log.w(TAG, "buildPreviewAndSize() sampleSize: " + sampleSize + ", orig: " + optOriginal.outWidth + "x" + optOriginal.outHeight + ", preview: " + previewWidth + "x" + previewHeight); } else { sampleSize = optOriginal.outHeight / previewHeightMax; previewHeight = previewHeightMax; previewWidth = (int) (1.0 * previewHeight * optOriginal.outWidth / optOriginal.outHeight); if (debug) Log.w(TAG, "buildPreviewAndSize() sampleSize: " + sampleSize + ", orig: " + optOriginal.outWidth + "x" + optOriginal.outHeight + ", preview: " + previewWidth + "x" + previewHeight); } BitmapFactory.Options optsPreview = new BitmapFactory.Options(); optsPreview.inSampleSize = sampleSize; //Bitmap decodedBmp = BitmapFactory.decodeFile(photoFile.getAbsolutePath(), optsPreview); Bitmap decodedBmp = BitmapFactory.decodeStream(new FileInputStream(imageFile), null, optsPreview); if (decodedBmp == null) { if (debug) Log.w(TAG, "buildPreviewAndSize() taking photo, but photo file cannot be decoded: " + imageFile.getPath()); return null; } if (debug) Log.w(TAG, "buildPreviewAndSize() decoded bitmap: " + decodedBmp.getWidth() + "x" + decodedBmp.getHeight() + ", " + decodedBmp.getByteCount() + " bytes "); Bitmap bmp = Bitmap.createScaledBitmap(decodedBmp, previewWidth, previewHeight, false); if (debug) Log.w(TAG, "buildPreviewAndSize() preview bitmap: " + bmp.getWidth() + "x" + bmp.getHeight() + ", " + bmp.getByteCount() + " bytes "); String fileName = "atlasPreview" + System.currentTimeMillis() + ".jpg"; final File previewFile = new File(tempDir, fileName); FileOutputStream fos = new FileOutputStream(previewFile); bmp.compress(Bitmap.CompressFormat.JPEG, 50, fos); fos.close(); FileInputStream fisPreview = new FileInputStream(previewFile) { public void close() throws IOException { super.close(); boolean deleted = previewFile.delete(); if (debug) Log.w(TAG, "buildPreviewAndSize() preview file is" + (!deleted ? " not" : "") + " removed: " + previewFile.getName()); } }; final MessagePart previewPart = layerClient.newMessagePart(MIME_TYPE_IMAGE_JPEG_PREVIEW, fisPreview, previewFile.length()); // prepare dimensions JSONObject joDimensions = new JSONObject(); try { joDimensions.put("width", optOriginal.outWidth); joDimensions.put("height", optOriginal.outHeight); joDimensions.put("orientation", 0); } catch (JSONException e) { throw new IllegalStateException("Cannot create JSON Object", e); } if (debug) Log.w(TAG, "buildPreviewAndSize() dimensions: " + joDimensions); final MessagePart dimensionsPart = layerClient.newMessagePart(MIME_TYPE_IMAGE_DIMENSIONS, joDimensions.toString().getBytes()); MessagePart[] previewAndSize = new MessagePart[] { previewPart, dimensionsPart }; return previewAndSize; }
From source file:edu.sfsu.csc780.chathub.ui.activities.MainActivity.java
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Log.d(TAG, "onActivityResult: request=" + requestCode + ", result=" + resultCode); if (requestCode == REQUEST_PICK_IMAGE && resultCode == Activity.RESULT_OK) { // Process selected image here // The document selected by the user won't be returned in the intent. // Instead, a URI to that document will be contained in the return intent // provided to this method as a parameter. // Pull that URI using resultData.getData(). if (data != null) { Uri uri = data.getData();//from ww w .j a va 2s .co m Log.i(TAG, "Uri: " + uri.toString()); // Resize if too big for messaging Bitmap bitmap = getBitmapForUri(uri); Bitmap resizedBitmap = scaleImage(bitmap); if (bitmap != resizedBitmap) { uri = savePhotoImage(resizedBitmap); } createImageMessage(uri); } else { Log.e(TAG, "Cannot get image for uploading"); } } else if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) { if (data != null && data.getExtras() != null) { Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data"); Log.d(TAG, "imageBitmap size:" + imageBitmap.getByteCount()); createImageMessage(savePhotoImage(imageBitmap)); } else { Log.e(TAG, "Cannot get photo URI after taking photo"); } } else if (requestCode == REQUEST_PREFERENCES) { if (DesignUtils.getPreferredTheme(this) != mSavedTheme) { DesignUtils.applyColorfulTheme(this); this.recreate(); } } else if (requestCode == REQUEST_NEW_CHANNEL && resultCode == Activity.RESULT_OK) { setChannelPage(); } }
From source file:com.tangjd.displayingbitmaps.util.ImageCache.java
/** * @param candidate - Bitmap to check/* w w w .ja va2 s .c o m*/ * @param targetOptions - Options that have the out* value populated * @return true if <code>candidate</code> can be used for inBitmap re-use with * <code>targetOptions</code> */ private static boolean canUseForInBitmap(Bitmap candidate, BitmapFactory.Options targetOptions) { if (!Utils.hasKitKat()) { // On earlier versions, the dimensions must match exactly and the inSampleSize must be 1 return candidate.getWidth() == targetOptions.outWidth && candidate.getHeight() == targetOptions.outHeight && targetOptions.inSampleSize == 1; } // From Android 4.4 (KitKat) onward we can re-use if the byte size of the new bitmap // is smaller than the reusable bitmap candidate allocation byte count. int width = targetOptions.outWidth / targetOptions.inSampleSize; int height = targetOptions.outHeight / targetOptions.inSampleSize; int byteCount = width * height * getBytesPerPixel(candidate.getConfig()); int allocationByteCount; if (Utils.hasKitKat()) { allocationByteCount = candidate.getAllocationByteCount(); } else if (Utils.hasHoneycombMR1()) { allocationByteCount = candidate.getByteCount(); } else { allocationByteCount = candidate.getRowBytes() * candidate.getHeight(); } return byteCount <= allocationByteCount; }
From source file:fr.forexperts.ui.ArticleListFragment.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 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 = new LruCache<String, Bitmap>(cacheSize) { @TargetApi(12)//from w w w. j av a 2 s .c o m @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; } } }; setHasOptionsMenu(true); }
From source file:edu.sfsu.csc780.chathub.ui.ChannelActivity.java
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Log.d(TAG, "onActivityResult: request=" + requestCode + ", result=" + resultCode); if (requestCode == REQUEST_PICK_IMAGE && resultCode == Activity.RESULT_OK) { // Process selected image here // The document selected by the user won't be returned in the intent. // Instead, a URI to that document will be contained in the return intent // provided to this method as a parameter. // Pull that URI using resultData.getData(). if (data != null) { Uri uri = data.getData();/*from w w w. ja v a 2 s. c om*/ Log.i(TAG, "Uri: " + uri.toString()); // Resize if too big for messaging Bitmap bitmap = getBitmapForUri(uri); Bitmap resizedBitmap = scaleImage(bitmap); if (bitmap != resizedBitmap) { uri = savePhotoImage(resizedBitmap); } createImageMessage(uri); } else { Log.e(TAG, "Cannot get image for uploading"); } } else if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) { if (data != null && data.getExtras() != null) { Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data"); Log.d(TAG, "imageBitmap size:" + imageBitmap.getByteCount()); createImageMessage(savePhotoImage(imageBitmap)); } else { Log.e(TAG, "Cannot get photo URI after taking photo"); } } else if (requestCode == REQUEST_PREFERENCES) { if (DesignUtils.getPreferredTheme(this) != mSavedTheme) { DesignUtils.applyColorfulTheme(this); this.recreate(); } } }
From source file:org.ros.android.rviz_for_android.drawable.loader.ColladaLoader.java
private ETC1Texture compressBitmap(Bitmap uncompressedBitmap) { // Rescale the bitmap to be half its current size Bitmap uncompressedBitmapResize = Bitmap.createScaledBitmap(uncompressedBitmap, uncompressedBitmap.getWidth() / 4, uncompressedBitmap.getHeight() / 4, true); uncompressedBitmap.recycle();//ww w . j a va 2s . c o m // Copy the bitmap to a byte buffer ByteBuffer uncompressedBytes = ByteBuffer.allocateDirect(uncompressedBitmapResize.getByteCount()) .order(ByteOrder.nativeOrder()); uncompressedBitmapResize.copyPixelsToBuffer(uncompressedBytes); uncompressedBytes.position(0); int width = uncompressedBitmapResize.getWidth(); int height = uncompressedBitmapResize.getHeight(); // Compress the texture int encodedSize = ETC1.getEncodedDataSize(width, height); ByteBuffer compressed = ByteBuffer.allocateDirect(encodedSize).order(ByteOrder.nativeOrder()); ETC1.encodeImage(uncompressedBytes, width, height, 2, 2 * width, compressed); ETC1Texture retval = new ETC1Texture(width, height, compressed); // We're done with the uncompressed bitmap, release it uncompressedBitmapResize.recycle(); return retval; }
From source file:com.laurencedawson.image_management.ImageManager.java
/** * Initialize a newly created ImageManager * @param context The application ofinal r activity context * @param cacheSize The size of the LRU cache * @param threads The number of threads for the pools to use *///from www.ja v a 2 s. c om public ImageManager(final Context context, final int cacheSize, final int threads) { // Instantiate the three queues. The task queue uses a custom comparator to // change the ordering from FIFO (using the internal comparator) to respect // request priorities. If two requests have equal priorities, they are // sorted according to creation date mTaskQueue = new PriorityBlockingQueue<Runnable>(QUEUE_SIZE, new ImageThreadComparator()); mActiveTasks = new ConcurrentLinkedQueue<Runnable>(); mBlockedTasks = new ConcurrentLinkedQueue<Runnable>(); // The application context mContext = context; // Create a new threadpool using the taskQueue mThreadPool = new ThreadPoolExecutor(threads, threads, Long.MAX_VALUE, TimeUnit.SECONDS, mTaskQueue) { @Override protected void beforeExecute(final Thread thread, final Runnable run) { // Before executing a request, place the request on the active queue // This prevents new duplicate requests being placed in the active queue mActiveTasks.add(run); super.beforeExecute(thread, run); } @Override protected void afterExecute(final Runnable r, final Throwable t) { // After a request has finished executing, remove the request from // the active queue, this allows new duplicate requests to be submitted mActiveTasks.remove(r); // Perform a quick check to see if there are any remaining requests in // the blocked queue. Peek the head and check for duplicates in the // active and task queues. If no duplicates exist, add the request to // the task queue. Repeat this until a duplicate is found synchronized (mBlockedTasks) { while (mBlockedTasks.peek() != null && !mTaskQueue.contains(mBlockedTasks.peek()) && !mActiveTasks.contains(mBlockedTasks.peek())) { Runnable runnable = mBlockedTasks.poll(); if (runnable != null) { mThreadPool.execute(runnable); } } } super.afterExecute(r, t); } }; // Calculate the cache size final int actualCacheSize = ((int) (Runtime.getRuntime().maxMemory() / 1024)) / cacheSize; // Create the LRU cache // http://developer.android.com/reference/android/util/LruCache.html // The items are no longer recycled as they leave the cache, turns out this wasn't the right // way to go about this and often resulted in recycled bitmaps being drawn // http://stackoverflow.com/questions/10743381/when-should-i-recycle-a-bitmap-using-lrucache mBitmapCache = new LruCache<String, Bitmap>(actualCacheSize) { protected int sizeOf(final String key, final Bitmap value) { return value.getByteCount() / 1024; } }; }