How Does One Use Glide to Download an Image into a Bitmap

How does one use glide to download an image into a bitmap?

Make sure you are on the Lastest version

implementation 'com.github.bumptech.glide:glide:4.10.0'

Kotlin:

Glide.with(this)
.asBitmap()
.load(imagePath)
.into(object : CustomTarget<Bitmap>(){
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
imageView.setImageBitmap(resource)
}
override fun onLoadCleared(placeholder: Drawable?) {
// this is called when imageView is cleared on lifecycle call or for
// some other reason.
// if you are referencing the bitmap somewhere else too other than this imageView
// clear it here as you can no longer have the bitmap
}
})

Bitmap Size:

if you want to use the original size of the image use the default constructor as above, else You can pass your desired size for bitmap

into(object : CustomTarget<Bitmap>(1980, 1080)

Java:

Glide.with(this)
.asBitmap()
.load(path)
.into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
imageView.setImageBitmap(resource);
}

@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});

Old Answer:

With compile 'com.github.bumptech.glide:glide:4.8.0' and below

Glide.with(this)
.asBitmap()
.load(path)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
imageView.setImageBitmap(resource);
}
});

For compile 'com.github.bumptech.glide:glide:3.7.0' and below

Glide.with(this)
.load(path)
.asBitmap()
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
imageView.setImageBitmap(resource);
}
});

Now you might see a warning SimpleTarget is deprecated

Reason:

The main point of deprecating SimpleTarget is to warn you about the
ways in which it tempts you to break Glide's API contract.
Specifically, it doesn't do anything to force you to stop using any
resource you've loaded once the SimpleTarget is cleared, which can
lead to crashes and graphical corruption.

The SimpleTarget still can be used as long you make sure you are not using the bitmap once the imageView is cleared.

Is there a way to load image as bitmap to Glide

For version 4 you have to call asBitmap() before load()

GlideApp.with(itemView.getContext())
.asBitmap()
.load(data.getImageUrl())
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {}
});
}

More info: http://bumptech.github.io/glide/doc/targets.html

Android Kotlin - Glide listener download image as Bitmap to variable and make placeholder onerror

Inside your load failed method you're not setting any image so try changing that also try adding the onerror() method below code implementation should fix it

try{
lateinit var bitmap:Bitmap
bitmap = Glide.with(context)
.asBitmap()
.placeholder(R.mipmap.avengerswallp)
.load(imgUri)
.error(getnothumb())
.listener(object : RequestListener<Bitmap>{
override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Bitmap>?, isFirstResource: Boolean): Boolean {
bitmap = myPlaceHolderBitmap
return true
}

override fun onResourceReady(resource: Bitmap?, model: Any?, target: Target<Bitmap>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
return false
}
}).submit().get()
}
catch(ex:Exception)
{
}

Save picture to storage using Glide


Update

1.Permissions in manifest file

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

  1. Need Coroutine to do some background work
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'

  1. Glide to get the image as a bitmap
CoroutineScope(Dispatchers.IO).launch {
saveImage(Glide.with(this@MainActivity)
.asBitmap()
.load("https://i.imgur.com/4HFRb2z.jpg") // sample image
.placeholder(android.R.drawable.progress_indeterminate_horizontal) // need placeholder to avoid issue like glide annotations
.error(android.R.drawable.stat_notify_error) // need error to avoid issue like glide annotations
.submit()
.get())
}

  1. Save the image in a newly created folder with the specific name
private fun saveImage(image: Bitmap): String? {
var savedImagePath: String? = null
val imageFileName = "JPEG_" + "FILE_NAME" + ".jpg"
val storageDir = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
.toString() + "/YOUR_FOLDER_NAME"
)
var success = true
if (!storageDir.exists()) {
success = storageDir.mkdirs()
}
if (success) {
val imageFile = File(storageDir, imageFileName)
savedImagePath = imageFile.getAbsolutePath()
try {
val fOut: OutputStream = FileOutputStream(imageFile)
image.compress(Bitmap.CompressFormat.JPEG, 100, fOut)
fOut.close()
} catch (e: Exception) {
e.printStackTrace()
}

// Add the image to the system gallery
galleryAddPic(savedImagePath)
//Toast.makeText(this, "IMAGE SAVED", Toast.LENGTH_LONG).show() // to make this working, need to manage coroutine, as this execution is something off the main thread
}
return savedImagePath
}

  1. Add the image to the gallery and do send broadcast (not mentioning much about as it's out of the question)
 private fun galleryAddPic(imagePath: String?) {
imagePath?.let { path ->
val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
val f = File(path)
val contentUri: Uri = Uri.fromFile(f)
mediaScanIntent.data = contentUri
sendBroadcast(mediaScanIntent)
}
}

Original

1.Permissions in manifest file

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

2.Glide to download the image as a bitmap

Glide.with(mContext)
.load("YOUR_URL")
.asBitmap()
.into(new SimpleTarget<Bitmap>(100,100) {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
saveImage(resource);
}
});

  1. Save the bitmap into your memory
    private String saveImage(Bitmap image) {
String savedImagePath = null;

String imageFileName = "JPEG_" + "FILE_NAME" + ".jpg";
File storageDir = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ "/YOUR_FOLDER_NAME");
boolean success = true;
if (!storageDir.exists()) {
success = storageDir.mkdirs();
}
if (success) {
File imageFile = new File(storageDir, imageFileName);
savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
image.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}

// Add the image to the system gallery
galleryAddPic(savedImagePath);
Toast.makeText(mContext, "IMAGE SAVED", Toast.LENGTH_LONG).show();
}
return savedImagePath;
}

private void galleryAddPic(String imagePath) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(imagePath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
}

Glide image from gallery to bitmap variable

I don't know if you should even think about doing this in some serious project but for now it did what needs to be done for me. Earlier I declared private Bitmap jopa.

Glide.with(getContext()).asBitmap().
load(selectedImage).override(500,500).
into(new CustomTarget<Bitmap>()
{
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
imgShare.setImageBitmap(resource);
jopa = ((BitmapDrawable)imgShare.getDrawable()).getBitmap();
}

@Override
public void onLoadCleared(@Nullable Drawable placeholder) {

}
});

Now Bitmap jopa can be used for other tasks. I hope. Tested it to change picture of another imageview, it worked, so I'll pray it will work further. Full onActivityResult code here. Don't want question to get too messy

How does one use glide to download an image into a drawable?

Instead of storing the image in memory, store the address instead.

private static final String[] IMAGES = {"https://google.com/someImage1.jpg", "https://google.com/someImage2.jpg"};

Then load the image when you instantiateItem

@Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.main_page_slidingimages, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
Glide.with(context)
.load(IMAGES.get(position))
.error(R.drawable.image1)
.into(imageView);
view.addView(imageLayout, 0);
return imageLayout;
}

Also, glide provides memory and disk caching. This means it should be able to show images even if there is no internet.



Related Topics



Leave a reply



Submit