programing

어떻게 글라이드를 사용하여 이미지를 비트맵으로 다운로드합니까?

jooyons 2023. 8. 8. 21:30
반응형

어떻게 글라이드를 사용하여 이미지를 비트맵으로 다운로드합니까?

에 URL 다운로드ImageViewGlide를 사용하면 매우 쉽습니다.

Glide
   .with(context)
   .load(getIntent().getData())
   .placeholder(R.drawable.ic_loading)
   .centerCrop()
   .into(imageView);

에 다운로드할 수 있는지 궁금합니다.Bitmap역시?다른 도구를 사용하여 조작할 수 있는 원시 비트맵으로 다운로드하고 싶습니다.코드를 살펴봤는데 어떻게 해야 할지 모르겠어요.

최신 버전인지 확인합니다.

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

코틀린:

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
            }
        })

비트맵 크기:

이미지의 원래 크기를 사용하려면 위와 같이 기본 생성자를 사용하십시오. 그렇지 않으면 원하는 비트맵 크기를 전달할 수 있습니다.

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) {
            }
        });

이전 답변:

와 함께compile 'com.github.bumptech.glide:glide:4.8.0'이하

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

위해서compile 'com.github.bumptech.glide:glide:3.7.0'이하

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

이제 경고가 표시될 수 있습니다.SimpleTarget is deprecated

이유:

SimpleTarget을 사용하지 않는 주된 이유는 Glide의 API 계약을 위반하도록 유혹하는 방법에 대해 경고하는 것입니다.특히 SimpleTarget을 지운 후 로드한 리소스의 사용을 중지하도록 강제하는 작업은 수행되지 않으므로 충돌과 그래픽 손상이 발생할 수 있습니다.

SimpleTargetimageView를 지운 후 비트맵을 사용하지 않는 한 계속 사용할 수 있습니다.

글라이드에 대해 잘 모르지만, 목표 크기를 알면 다음과 같은 것을 사용할 수 있습니다.

Bitmap theBitmap = Glide.
        with(this).
        load("http://....").
        asBitmap().
        into(100, 100). // Width and height
        get();

당신은 통과할 수 있을 것 같습니다.-1,-1전체 크기의 이미지를 얻을 수 있습니다(테스트에 따라 달라지며 문서화된 이미지를 볼 수 없음).

메모into(int,int)를 반환합니다.FutureTarget<Bitmap>그래서 당신은 이것을 시도해 보는 블록 덮개로 포장해야 합니다.ExecutionException그리고.InterruptedException테스트를 거쳐 작동하는 보다 완벽한 구현 예는 다음과 같습니다.

class SomeActivity extends Activity {

    private Bitmap theBitmap = null;
        
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // onCreate stuff ...
        final ImageView image = (ImageView) findViewById(R.id.imageView);

        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                Looper.prepare();
                try {
                    theBitmap = Glide.
                        with(SomeActivity.this).
                        load("https://www.google.es/images/srpr/logo11w.png").
                        asBitmap().
                        into(-1,-1).
                        get();
                 } catch (final ExecutionException e) {
                     Log.e(TAG, e.getMessage());
                 } catch (final InterruptedException e) {
                     Log.e(TAG, e.getMessage());
                 }
                 return null;
            }
            @Override
            protected void onPostExecute(Void dummy) {
                if (null != theBitmap) {
                    // The full bitmap should be available here
                    image.setImageBitmap(theBitmap);
                    Log.d(TAG, "Image loaded");
                };
            }
        }.execute();
    }
}

아래 댓글에서 Monkeyless의 제안에 따라(그리고 이것도 공식적인 방법으로 보입니다), 당신은 다음을 사용할 수 있습니다.SimpleTarget선택적으로 와 결합된.override(int,int)코드를 상당히 단순화합니다.그러나 이 경우 정확한 크기를 제공해야 합니다(1 미만은 허용되지 않음).

Glide
    .with(getApplicationContext())
    .load("https://www.google.es/images/srpr/logo11w.png")
    .asBitmap()
    .into(new SimpleTarget<Bitmap>(100,100) {
        @Override
        public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
            image.setImageBitmap(resource); // Possibly runOnUiThread()
        }
    });

동일한 이미지가 필요한 경우 @henry가 제안한 대로 사용합니다.

갱신하다

 bitmap = Glide.with(c).asBitmap().load( "url").submit().get();

그것은 그것을 무시하는 것처럼 보입니다.Target클래스 또는 같은 구현 중 하나.BitmapImageViewTarget그리고 그 위에.setResource비트맵을 캡처하는 방법이 방법일 수 있습니다...

이것은 테스트되지 않았습니다. :-)

    Glide.with(context)
         .load("http://goo.gl/h8qOq7")
         .asBitmap()
         .into(new BitmapImageViewTarget(imageView) {
                     @Override
                     protected void setResource(Bitmap resource) {
                         // Do bitmap magic here
                         super.setResource(resource);
                     }
         });

갱신하다

이제 우리는 사용해야 합니다.

샘플 코드

    Glide.with(mContext)
            .asBitmap()
            .load("url")
            .into(new CustomTarget<Bitmap>() {
                @Override
                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {

                }

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

어떻게 글라이드를 사용하여 이미지를 비트맵으로 다운로드합니까?

위의 모든 답변은 정확하지만 구식입니다.

글라이드의 implementation 'com.github.bumptech.glide:glide:4.8.0'

코드에서 아래 오류를 찾을 수 있습니다.

  • 에서 사용할 수 없습니다.

enter image description here

  • SimpleTarget<Bitmap> 사용되지 않습니다.

enter image description here

해결 방법은 다음과 같습니다.

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.Request;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SizeReadyCallback;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;



public class MainActivity extends AppCompatActivity {

    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = findViewById(R.id.imageView);

        Glide.with(this)
                .load("")
                .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE))
                .into(new Target<Drawable>() {
                    @Override
                    public void onLoadStarted(@Nullable Drawable placeholder) {

                    }

                    @Override
                    public void onLoadFailed(@Nullable Drawable errorDrawable) {

                    }

                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {

                        Bitmap bitmap = drawableToBitmap(resource);
                        imageView.setImageBitmap(bitmap);
                        // now you can use bitmap as per your requirement
                    }

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

                    }

                    @Override
                    public void getSize(@NonNull SizeReadyCallback cb) {

                    }

                    @Override
                    public void removeCallback(@NonNull SizeReadyCallback cb) {

                    }

                    @Override
                    public void setRequest(@Nullable Request request) {

                    }

                    @Nullable
                    @Override
                    public Request getRequest() {
                        return null;
                    }

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onStop() {

                    }

                    @Override
                    public void onDestroy() {

                    }
                });

    }

    public static Bitmap drawableToBitmap(Drawable drawable) {

        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        int width = drawable.getIntrinsicWidth();
        width = width > 0 ? width : 1;
        int height = drawable.getIntrinsicHeight();
        height = height > 0 ? height : 1;

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return bitmap;
    }
}

이것이 제게 도움이 되었습니다. https://github.com/bumptech/glide/wiki/Custom-targets#overriding-default-behavior

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.transition.Transition;
import com.bumptech.glide.request.target.BitmapImageViewTarget;

...

Glide.with(yourFragment)
  .load("yourUrl")
  .asBitmap()
  .into(new BitmapImageViewTarget(yourImageView) {
    @Override
    public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> anim) {
        super.onResourceReady(bitmap, anim);
        Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {  
            @Override
            public void onGenerated(Palette palette) {
                // Here's your generated palette
                Palette.Swatch swatch = palette.getDarkVibrantSwatch();
                int color = palette.getDarkVibrantColor(swatch.getTitleTextColor());
            }
        });
    }
});

비트맵 변수에 동적 비트맵 이미지를 할당하려는 경우

예:kotlin

backgroundImage = Glide.with(applicationContext).asBitmap().load(PresignedUrl().getUrl(items!![position].img)).submit(100, 100).get();

위의 답변은 저에게 효과가 없었습니다.

.asBitmap 앞에 있어야 ..load("http://....")

새 버전에 대한 업데이트

Glide.with(context.applicationContext)
    .load(url)
    .listener(object : RequestListener<Drawable> {
        override fun onLoadFailed(
            e: GlideException?,
            model: Any?,
            target: Target<Drawable>?,
            isFirstResource: Boolean
        ): Boolean {
            listener?.onLoadFailed(e)
            return false
        }

        override fun onResourceReady(
            resource: Drawable?,
            model: Any?,
            target: com.bumptech.glide.request.target.Target<Drawable>?,
            dataSource: DataSource?,
            isFirstResource: Boolean
        ): Boolean {
            listener?.onLoadSuccess(resource)
            return false
        }

    })
    .into(this)

이전 답변

@outlayer의 대답은 맞지만, 새로운 Glide 버전에 약간의 변화가 있습니다.

내 버전: 4.7.1

코드:

 Glide.with(context.applicationContext)
                .asBitmap()
                .load(iconUrl)
                .into(object : SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
                    override fun onResourceReady(resource: Bitmap, transition: com.bumptech.glide.request.transition.Transition<in Bitmap>?) {
                        callback.onReady(createMarkerIcon(resource, iconId))
                    }
                })

참고: 이 코드는 UI 스레드에서 실행되므로 비동기 작업, 실행기 또는 다른 기능을 동시에 사용할 수 있습니다(예: @outlayer의 코드).원래 크기를 원하신다면 Target을 넣어주세요.SIZE_ORIGINA를 내 코드로 사용합니다.-1, -1 사용 안 함

Glide 버전 4.10.0의 경우: Glide.with(context).다운로드(mImageUrl).을 제출하다

코틀린 함수

inline fun getBitmap(imageUrl: String, block: (Bitmap?) -> Unit) {
        return try {
            val url = URL(imageUrl)
            val image = BitmapFactory.decodeStream(url.openConnection().getInputStream())
            block(image)
        } catch (e: IOException) {
            println(e)
            block(null)
        }
    }

최신 버전:

GlideApp.with(imageView)
    .asBitmap()
    .override(200, 200)
    .centerCrop()
    .load(mUrl)
    .error(R.drawable.defaultavatar)
    .diskCacheStrategy(DiskCacheStrategy.ALL)
    .signature(ObjectKey(System.currentTimeMillis() / (1000*60*60*24))) //refresh avatar cache every day
    .into(object : CustomTarget<Bitmap>(){
        override fun onLoadCleared(placeholder: Drawable?) {}
        override fun onLoadFailed(errorDrawable: Drawable?) {
            //add context null check in case the user left the fragment when the callback returns
            context?.let { imageView.addImage(BitmapFactory.decodeResource(resources, R.drawable.defaultavatar)) }
        }
        override fun onResourceReady(
            resource: Bitmap,
            transition: Transition<in Bitmap>?) { context?.let { imageView.addImage(resource) } }
    })

코틀린의 방식 -

fun Context.bitMapFromImgUrl(imageUrl: String, callBack: (bitMap: Bitmap) -> Unit) {
    GlideApp.with(this)
        .asBitmap()
        .load(imageUrl)
        .into(object : CustomTarget<Bitmap>() {
            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                callBack(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
            }
        })
}

코틀린으로 사용할 수 있습니다.

CoroutineScope(Dispatchers.IO).launch {
      Glide.with(this@&YourActivity).asBitmap().load(imageUrl)                           
                        .listener(object : RequestListener<Bitmap> {
                            override fun onLoadFailed(
                                e: GlideException?,
                                model: Any?,
                                target: Target<Bitmap>?,
                                isFirstResource: Boolean
                            ): Boolean {
                                  Log.e("GlideException" ,"${e.message}")
                                return false
                            }

                            override fun onResourceReady(
                                resource: Bitmap?,
                                model: Any?,
                                target: Target<Bitmap>?,
                                dataSource: DataSource?,
                                isFirstResource: Boolean
                            ): Boolean {
                                resource?.let {bitmap->
                                    //here your bitmap is ready you can use it
                                }
                                return false
                            }

                        })
                        .submit().get()//by using this line glide lib behave as synchronously(block instructions until the task is completed) and by removing this line you can use it as a asynchronously(without blocking other operations)  
}

사용 중

api 'com.github.bumptech.glide:glide:4.12.0'
kapt 'com.github.bumptech.glide:compiler:4.12.0'

전체 답변

지금 글라이드는 URL이 잘못되면 앱을 크래시하기 때문에 트라이캐치 블록을 추가해야 했습니다.

  return try {
            Glide.with(context)
                .asBitmap()
                .load(imageURL)
                .listener(object : RequestListener<Bitmap> {
                    override fun onLoadFailed(
                        e: GlideException?,
                        model: Any?,
                        target: Target<Bitmap>?,
                        isFirstResource: Boolean
                    ): Boolean {
                        Log.e(
                            TAG,
                            "Texture from ResourceID $resourceId could not be Loaded. " +
                                    "Using default Texture"
                        )
                        return false
                    }

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

이 예에서는 이미지를 비트맵으로 다운로드하기 위해 글라이드합니다.

1단계 - build.gradle에 다음의 종속성을 추가합니다. 모듈:

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

2단계 - res/layout/activity_main.xml에 다음 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <ImageView
      android:id="@+id/imageView"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />
</RelativeLayout>

3단계 - 다음 코드를 src/MainActivity.java에 추가합니다.

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
public class MainActivity extends AppCompatActivity {
   ImageView imageView;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      imageView = findViewById(R.id.imageView);
      Glide.with(this).asBitmap().load("https://www.google.es/images/srpr/logo11w.png").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) {
         }
      });
   }
}

4단계 - 다음 코드를 AndroidManifest.xml에 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <uses-permission android:name="android.permission.INTERNET"/>
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
         <activity android:name=".MainActivity">
            <intent-filter>
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
         </activity>
   </application>
</manifest>

응용 프로그램을 실행해 보겠습니다.

최신 버전의 글라이드에서 우리는 이것을 할 수 있습니다.

val bitmap = Glide.with(context)
        .asBitmap()
        .load("url")
        .submit()
        .get()

언급URL : https://stackoverflow.com/questions/27394016/how-does-one-use-glide-to-download-an-image-into-a-bitmap

반응형