- Android glide get bitmap
- Customizing requests.
- ListView and RecyclerView
- Non-View Targets
- Background Threads
- Access Bitmap from Glide target #1083
- Comments
- bslaghtSFDC commented Mar 23, 2016
- TWiStErRob commented Mar 23, 2016
- Android glide get bitmap
- Why should we use hardware Bitmaps?
- How do we enable hardware Bitmaps?
- How do we disable hardware Bitmaps?
- What’s broken when we use hardware Bitmaps?
- What’s less efficient when we use hardware Bitmaps?
- How to load or resize a Bitmap from a Bitmap using Glide ? #2651
- Comments
- michaelDnguyen commented Nov 29, 2017 •
- Displaying Images with the Glide Library
Android glide get bitmap
Loading images with Glide is easy and in many cases requires only a single line:
Cancelling loads you no longer need is simple too:
Although it’s good practice to clear loads you no longer need, you’re not required to do so. In fact, Glide will automatically clear the load and recycle any resources used by the load when the Activity or Fragment you pass in to Glide.with() is destroyed.
Customizing requests.
Glide offers a variety of options that can be applied to individual requests, including transformations, transitions, caching options etc.
Default options can be applied directly on a request:
Options can be shared across requests using the RequestOptions class:
Glide’s API can be further extended to include custom options using Glide’s generated API for advanced use cases.
ListView and RecyclerView
Loading images in a ListView or RecyclerView uses the same load line as if you were loading in to a single View. Glide handles View re-use and request cancellation automatically:
You don’t need to null check your urls either, Glide will either clear out the view or set whatever placeholder Drawable or fallback Drawable you’ve specified if the url is null.
Glide’s sole requirement is that any re-usable View or Target that you may have started a load into at a previous position either has a new loaded started into it or is explicitly cleared via the clear() API.
By calling clear() or into(View) on the View , you’re cancelling the load and guaranteeing that Glide will not change the contents of the view after the call completes. If you forget to call clear() and don’t start a new load, the load you started into the same View for a previous position may complete after you set your special Drawable and change the contents of the View to an old image.
Although the examples we’ve shown here are for RecyclerView, the same principles apply to ListView as well.
Non-View Targets
In addition to loading Bitmap s and Drawable s into View s, you can also start asynchronous loads into your own custom Target s:
There are a few gotchas with using custom Target s, so be sure to check out the Targets docs page for details.
Background Threads
Loading images on background threads is also straight forward using submit(int, int) :
You can also start asynchronous loads on background threads the same way you would on a foreground thread if you don’t need the Bitmap or Drawable on the background thread itself:
Источник
Access Bitmap from Glide target #1083
Comments
bslaghtSFDC commented Mar 23, 2016
Glide Version:3.6.1
Integration libraries:no
Device/Android Version:Fails on all devices
So I am using Glide to load a web url .into imageviews in a gridview successfully. In each of these grid elements, I have an onclick listener through which I want to pass the Glide bitmap to a new activity. I know I can aquire the bitmap from glide with a callback, but for memory reasons (there are a lot of images) I do not want essentially two copies of all the images in memory.
So I am trying to only load the one that actually needs to be passed by accessing it in the onClickListener of the gridview element:
However, I get an exception java.lang.ClassCastException: com.bumptech.glide.request.target.SquaringDrawable cannot be cast to android.graphics.drawable.BitmapDrawable , presumably because Glide has its own object in the ImageView. I cannot find any documentation on the SquaringDrawable.
tl;dr: How can I get a bitmap from an ImageView that Glide was used on in the far future, after Glide has done it’s thing?
The text was updated successfully, but these errors were encountered:
TWiStErRob commented Mar 23, 2016
ImageView.getDrawable() is not a safe operation, especially not in your use case. If you hold on to a Bitmap and for whatever reason it is needed to clear the ImageView the Bitmap would be reused or even recycled, essentially becoming unusable from your point of view.
Anything delivered to a target (in your case ImageView) is only valid between onResourceReady and onLoadCleared (see Target and descendants). Even if you capture it via a listener this may be true.(Btw, having two references to a Bitmap doesn’t duplicate the memory, they just both point to the same memory.)
If you want to display the same Bitmap in another view Glide.load it again the same way you did earlier. This should hit the memory cache and give you the same Bitmap. If you share your grid’s Glide load line, layout and what you want to do with the Bitmap, I can be more specific.
If you persist to go your way the Drawable that you get by default most of the time is GlideBitmapDrawable which may or may not be wrapped in squaring, so you can acquire the Bitmap via:
Or if you add .asBitmap() to the load you can be sure getDrawable() returns a BitmapDrawable . Note that otherwise sometimes even the above line would fail: if the source image is an animated GIF. This is undocumented because you needn’t know about it, what you can be sure that it’s a GlideDrawable , just check the generics of .listener() or the return value of .into() . It gives Glide freedom to make internal changes and users a signal that there’s something fishy going on when they encounter exception.
Источник
Android glide get bitmap
Bitmap.Config.HARDWARE is a new Bitmap format that was added in Android O. Hardware Bitmaps store pixel data only in graphics memory and are optimal for cases where the Bitmap is only drawn to the screen.
Why should we use hardware Bitmaps?
Only one copy of pixel data is stored for hardware Bitmaps . Normally there’s one copy of pixel data in application memory (the pixel byte array) and one copy in graphics memory (after the pixels are uploaded to the GPU). Hardware Bitmaps retain only the copy uploaded to the GPU. As a result:
- Hardware Bitmaps require ½ the memory of other Bitmap configurations
- Hardware Bitmaps avoid jank caused by texture uploads at draw time.
How do we enable hardware Bitmaps?
For now, you need to set an explicit RequestOption to enable hardware Bitmaps:
Sadly we’re finding a number of cases where using Hardware Bitmaps leads to crashes on some devices. I’d only recommend default enabling hardware Bitmaps on Android 9 (API 28) or higher.
In the long run we hope that Glide will load hardware Bitmaps by default and no changes will be needed to enable the format, only to disable it.
How do we disable hardware Bitmaps?
If you need to disable hardware Bitmaps , you should try to do so only for requests where you need to do one of the slow or broken things below. You can disable hardware Bitmaps for a particular request using disallowHardwareConfig() :
What’s broken when we use hardware Bitmaps?
Storing pixel data in graphics memory means that the pixel data isn’t readily accessible, which will cause exceptions in some cases. All of the known cases are listed below:
- Reading/writing pixel data in Java, including:
- Bitmap#getPixel
- Bitmap#getPixels
- Bitmap#copyPixelsToBuffer
- Bitmap#copyPixelsFromBuffer
- Reading/writing pixel data in native code
- Rendering hardware Bitmaps with a software Canvas:
Opening too many file descriptors.
Each hardware Bitmap consumes a file descriptor. There’s a per process FD limit (O & earlier typically 1024, in some builds of O-MR1 & higher it’s 32k). Glide attempts to limit the number of hardware Bitmaps allocated to stay under the limit, but if you’re already allocating large numbers of FDs, this may be an issue.
Screenshots triggered by code that try to draw the view hierarchy with Canvas .
PixelCopy can be used instead on O+.
Shared element transitions (fixed in OMR1) An example trace will look something like this:
This might be caused by a race between the render of the first frame and the first hardware bitmap decode. If the hardware bitmap decode wins, we NPE. Unfortunately attempts to force Glide to wait to use hardware bitmaps until after a frame has been rendered haven’t eliminated this issue. Either the implementation in Glide is missing some number of cases or there’s some other issue on O that produces a similar stack trace.
Another trace that might be from the same cause:
What’s less efficient when we use hardware Bitmaps?
In some cases to avoid breaking users, the Bitmap class will perform an expensive copy of the graphics memory. In some cases where any of these methods are used, you should consider avoiding using the hardware Bitmap configuration to begin with depending on the frequency the slow methods are used. If you do use these methods, the framework will log a message: “Warning attempt to read pixels from hardware bitmap, which is very slow operation” and also trigger a StrictMode#noteSlowCall .
Источник
How to load or resize a Bitmap from a Bitmap using Glide ? #2651
Comments
michaelDnguyen commented Nov 29, 2017 •
Glide Version: 4.3.1
Integration libraries: No
Device/Android Version: Android API > 16
Issue details / Repro steps / Use case background:
Glide load line / GlideModule (if any) / list Adapter code (if any):
How to load resize a bitmap from a bitmap using Glide ? Example code:
Bitmap bitOrigin = Glide.with(getActivity()).asBitmap().load(url).submit().get(); //process a bitmap. Bitmap bitResult = Glide.with(getActivity()).asBitmap().load(bitOrigin).submit(1000,1000).get();Stack trace / LogCat:
11-30 09:05:42.352: W/System.err(12765): java.lang.NullPointerException: Attempt to invoke virtual method ‘int android.graphics.Bitmap.getWidth()’ on a null object reference 11-30 09:05:42.355: W/System.err(12765): at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:750) 11-30 09:05:42.355: W/System.err(12765): at com.scanlibrary.ResultFragment$SaveAndAddPageClickListener$1.run(ResultFragment.java:291) 11-30 09:05:42.355: W/System.err(12765): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 11-30 09:05:42.355: W/System.err(12765): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 11-30 09:05:42.355: W/System.err(12765): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 11-30 09:05:42.355: W/System.err(12765): at java.lang.Thread.run(Thread.java:762)thanks & best regards,
The text was updated successfully, but these errors were encountered:
Источник
Displaying Images with the Glide Library
Glide is an Image Loader Library for Android developed by bumptech and is a library that is recommended by Google. It has been used in many Google open source projects including Google I/O 2014 official application. It provides animated GIF support and handles image loading/caching.
Add to your app/build.gradle file:
Make sure to create a MyAppGlideModule that simply extends from AppGlideModule and has the @GlideModule annotation. For now, the class is empty but later we will show how it can be used to set the default image resolution. If you upgrading from Glide v3, make sure you follow this step too:
Make sure to sync your project to Gradle before continuing, since Glide needs to generate the necessary code to invoke GlideApp.with() in Android Studio.
If you are migrating from Glide v3, make sure to review this guide. Instead of Glide.with() , you will need to use GlideApp.with() :
Resizing images with:
Placeholder and error images:
Cropping images with:
Modify your MyAppGlideModule to override applyOptions:
Ideally, an image’s dimensions would match exactly those of the ImageView in which it is being displayed, but as this is often not the case, care must be taken to resize and/or scale the image appropriately. Android’s native support for this isn’t robust, especially when displaying very large images (such as bitmaps returned from the camera) in smaller image views, which can often lead to errors (see Troubleshooting).
Glide automatically limits the size of the image it holds in memory to the ImageView dimensions. Picasso has the same ability, but requires a call to fit() . With Glide, if you don’t want the image to be automatically fitted to the ImageView , you can call override(horizontalSize, verticalSize) . This will resize the image before displaying it in the ImageView but without respect to the image’s aspect ratio:
Resizing images in this way without respect to the original aspect ratio will often make the image appear skewed or distorted. In most cases, this should be avoided, and Glide offers two standard scaling transformation options to prevent this: centerCrop and fitCenter .
If you only want to resize one dimension, use Target.SIZE_ORIGINAL as a placeholder for the other dimension:
Calling centerCrop() scales the image so that it fills the requested bounds of the ImageView and then crops the extra. The ImageView will be filled completely, but the entire image might not be displayed.
Calling fitCenter() scales the image so that both dimensions are equal to or less than the requested bounds of the ImageView . The image will be displayed completely, but might not fill the entire ImageView .
If an image or set of images aren’t loading, make sure to check the Android monitor log in Android Studio. There’s a good chance you might see an java.lang.OutOfMemoryError «Failed to allocate a [. ] byte allocation with [. ] free bytes» or a Out of memory on a 51121168-byte allocation. . This is quite common and means that you are loading one or more large images that have not been properly resized.
First, you have to find which image(s) being loaded are likely causing this error. For any given Glide . call, we can fix this by one or more of the following approaches:
- Add an explicit width or height to the ImageView by setting layout_width=500dp in the layout file.
- Call .override(width, height) during the Glide load and explicitly set a width or height for the image such as: GlideApp.with(. ).load(imageUri).override(500, 500).into(. ) .
- Try removing android:adjustViewBounds=»true» from your ImageView if present and if you not calling .override()
- Open up your static placeholder or error images and make sure their dimensions are relatively small ( AndroidManifest.xml and then add android:largeHeap to your manifest:
Note that this is not generally a good idea, but can be used temporarily to trigger fewer out of memory errors.
If you experience errors loading images, you can create a RequestListener and pass it in via Glide.listener() to intercept errors:
Transformations are supported by an additional third-party library, glide-transformations. First, add the dependencies:
Источник