简体   繁体   English

有没有办法将图像作为位图加载到 Glide

[英]Is there a way to load image as bitmap to Glide

Im looking for a way to use bitmap as input to Glide.我正在寻找一种使用位图作为 Glide 输入的方法。 I am even not sure if its possible.我什至不确定它是否可能。 It's for resizing purposes.它用于调整大小。 Glide has a good image enhancement with scale. Glide 具有良好的图像增强与缩放。 The problem is that I have resources as bitmap already loaded to memory.问题是我有资源作为位图已经加载到内存中。 The only solution I could find is to store images to temporary file and reload them back to Glide as inputStream/file.. Is there a better way to achieve that ?我能找到的唯一解决方案是将图像存储到临时文件并将它们重新加载回 Glide 作为 inputStream/file.. 有没有更好的方法来实现这一点?

Please before answering .. Im not talking about output from Glide.. .asBitmap().get() I know that.I need help with input.请在回答之前.. 我​​不是在谈论 Glide 的输出.. .asBitmap().get()我知道。我需要输入方面的帮助。

Here is my workaround solution:这是我的解决方法:

 Bitmap bitmapNew=null;
        try {
            //
            ContextWrapper cw = new ContextWrapper(ctx);
            File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
            File file=new File(directory,"temp.jpg");
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
            fos.close();
            //
            bitmapNew = Glide
                    .with(ctx)
                    .load(file)
                    .asBitmap()
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .skipMemoryCache(true)
                    .into( mActualWidth, mActualHeight - heightText)
                    .get();

            file.delete();
        } catch (Exception e) {
            Logcat.e( "File not found: " + e.getMessage());
        }

I'd like to avoid writing images to internal and load them again.That is the reason why Im asking if there is way to to have input as bitmap我想避免将图像写入内部并再次加载它们。这就是为什么我问是否有办法将输入作为位图

Thanks谢谢

For version 4 you have to call asBitmap() before load()对于版本 4,您必须在asBitmap()之前调用asBitmap() 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更多信息: http : //bumptech.github.io/glide/doc/targets.html

This solution is working with Glide V4.此解决方案适用于 Glide V4。 You can get the bitmap like this:您可以像这样获取位图:

Bitmap bitmap = Glide
    .with(context)
    .asBitmap()
    .load(uri_File_String_Or_ResourceId)
    .submit()
    .get();

Note: this will block the current thread to load the image.注意:这将阻止当前线程加载图像。

A really strange case, but lets try to solve it.一个非常奇怪的案例,但让我们尝试解决它。 I'm using the old and not cool Picasso , but one day I'll give Glide a try.我正在使用旧的、不酷的Picasso ,但总有一天我会尝试一下 Glide。 Here are some links that could help you :以下是一些可以帮助您的链接:

And actually a cruel but I think efficient way to solve this :实际上是一种残酷但我认为解决此问题的有效方法:

ByteArrayOutputStream stream = new ByteArrayOutputStream();
  yourBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
  Glide.with(this)
      .load(stream.toByteArray())
      .asBitmap()
      .error(R.drawable.ic_thumb_placeholder)
      .transform(new CircleTransform(this))
      .into(imageview);

I'm not sure if this will help you, but I hope it can make you a step closer to the solution.我不确定这是否会对您有所帮助,但我希望它能让您更接近解决方案。

There is little changes according to latest version of Glide .根据最新版本的Glide几乎没有变化。 Now we need to use submit() to load image as bitmap, if you do not class submit() than listener won't be called.现在我们需要使用submit()将图像加载为位图,如果您不类submit()则不会调用侦听器。

here is working example i used today.这是我今天使用的工作示例。

Glide.with(cxt)
  .asBitmap().load(imageUrl)
  .listener(new RequestListener<Bitmap>() {
      @Override
      public boolean onLoadFailed(@Nullable GlideException e, Object o, Target<Bitmap> target, boolean b) {
          Toast.makeText(cxt,getResources().getString(R.string.unexpected_error_occurred_try_again),Toast.LENGTH_SHORT).show();
          return false;
      }

      @Override
      public boolean onResourceReady(Bitmap bitmap, Object o, Target<Bitmap> target, DataSource dataSource, boolean b) {
          zoomImage.setImage(ImageSource.bitmap(bitmap));
          return false;
      }
  }
).submit();

It is working and I'm getting bitmap from listener.它正在工作,我正在从侦听器获取位图。

Please use Implementation for that is:请为此使用实现:

implementation 'com.github.bumptech.glide:glide:4.9.0'实现 'com.github.bumptech.glide:glide:4.9.0'

     Glide.with(this)
     .asBitmap()
      .load("http://url")
    .into(new CustomTarget <Bitmap>() {   
@Override  
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition <? super Bitmap> transition) { 
                // you can do something with loaded bitmap here

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

Most of the API's and methods of Glide are now deprecated. Glide 的大部分 API 和方法现在都已弃用。 Below is working for Glide 4.9 and upto Android 10.以下适用于 Glide 4.9 和 Android 10。

For image URI对于图像 URI

  Bitmap bitmap = Glide
    .with(context)
    .asBitmap()
    .load(image_uri_or_drawable_resource_or_file_path)
    .submit()
    .get();

Use Glide as below in build.gradle在 build.gradle 中使用 Glide 如下

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

The accepted answer works for previous versions, but in new versions of Glide use:接受的答案适用于以前的版本,但在 Glide 的新版本中使用:

RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(android.R.drawable.waiting);
requestOptions.error(R.drawable.waiting);
Glide.with(getActivity()).apply(requestOptions).load(imageUrl).into(imageView);

Courtesy 礼貌

here's another solution which return you a bitmap to set into your ImageView这是另一个解决方案,它返回一个位图以设置到您的 ImageView

Glide.with(this)
            .load(R.drawable.card_front)    // you can pass url too
            .asBitmap()
            .into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                    // you can do something with loaded bitmap here

                    imgView.setImageBitmap(resource);
                }
            });

This worked for me in recent version of Glide:这在最近版本的 Glide 中对我有用:

Glide.with(this)
        .load(bitmap)
        .dontTransform()
        .into(imageView);

For what is is worth, based upon the posts above, my approach:对于什么是值得的,根据上面的帖子,我的方法是:

     Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri imageUri = Uri.withAppendedPath(sArtworkUri, String.valueOf(album_id));

then in the adapter:然后在适配器中:

        //  loading album cover using Glide library

    Glide.with(mContext)
            .asBitmap()
            .load(imageUri)
            .into(holder.thumbnail);

In Kotlin,在科特林,

Glide.with(this)
            .asBitmap()
            .load("https://...")
            .addListener(object : RequestListener<Bitmap> {
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<Bitmap>?,
                    isFirstResource: Boolean
                ): Boolean {
                    Toast.makeText(this@MainActivity, "failed: " + e?.printStackTrace(), Toast.LENGTH_SHORT).show()
                    return false
                }

                override fun onResourceReady(
                    resource: Bitmap?,
                    model: Any?,
                    target: Target<Bitmap>?,
                    dataSource: DataSource?,
                    isFirstResource: Boolean
                ): Boolean {
                    //image is ready, you can get bitmap here
                    return false
                }

            })
            .into(imageView)

Updated answer 2021 Aug 2021 年 8 月更新答案

Glide.with(context)
      .asBitmap()
      .load(uri)
      .into(new CustomTarget<Bitmap>() {
          @Override
          public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
              useIt(resource);
          }

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

onResourceReady : The method that will be called when the resource load has finished. onResourceReady :资源加载完成后将调用的方法。
resource parameter is the loaded resource. resource参数是加载的资源。

onLoadCleared : A mandatory lifecycle callback that is called when a load is cancelled and its resources are freed. onLoadCleared :在取消加载并释放其资源时调用的强制性生命周期回调。 You must ensure that any current Drawable received in onResourceReady is no longer used before redrawing the container (usually a View) or changing its visibility.在重绘容器(通常是视图)或更改其可见性之前,您必须确保不再使用在onResourceReady 中接收到的任何当前 Drawable。
placeholder parameter is the placeholder drawable to optionally show, or null. placeholder参数是可绘制的占位符,可选择显示,或为 null。

2021 年:

  val bitmap=Glide.with(this).asBitmap().load(imageUri).submit().get()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM