使用Glide库显示模糊图像

8
我会尽力帮助您翻译中文。以下是需要翻译的内容:

我正在尝试使用Glide显示模糊图像,但只显示错误图像。我不知道为什么会显示错误图像。URL没问题,但仍然只显示错误图像。

这是我的代码

 Glide.with(context)
                .load("http://www.gadgetsaint.com/wp-content/uploads/2016/11/cropped-web_hi_res_512.png")
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .bitmapTransform(new BlurTransformation(context))
                .error(R.drawable.error_image)
                .into(imageView);

模糊变换类:

public class BlurTransformation extends BitmapTransformation {

private RenderScript rs;

public BlurTransformation(Context context) {
    super(context);

    rs = RenderScript.create(context);
}

@SuppressLint("NewApi")
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
    Bitmap blurredBitmap = toTransform.copy(Bitmap.Config.ARGB_8888, true);

    // Allocate memory for Renderscript to work with
    Allocation input = Allocation.createFromBitmap(
            rs,
            blurredBitmap,
            Allocation.MipmapControl.MIPMAP_FULL,
            Allocation.USAGE_SHARED
    );
    Allocation output = Allocation.createTyped(rs, input.getType());

    // Load up an instance of the specific script that we want to use.
    ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
    script.setInput(input);

    // Set the blur radius
    script.setRadius(100);

    // Start the ScriptIntrinisicBlur
    script.forEach(output);

    // Copy the output to the blurred bitmap
    output.copyTo(blurredBitmap);

    toTransform.recycle();

    return blurredBitmap;
}

@Override
public String getId() {
    return "blur";
}
}
5个回答

21
  1. 添加这个库: implementation 'jp.wasabeef:glide-transformations:4.0.0' 要获取最新版本,请从此处的更改日志中查看 Glide transformation
  2. 在需要模糊图片的地方,将此代码应用于您的视图
    Glide.with(this)
     .load(R.drawable.demo)
     .apply(bitmapTransform(BlurTransformation(25, 3)))
     .into(imageView)

请查看 changeLog 获取最新版本 :) - Steve Moretz
这个库是开源的吗?可以使用吗? - Silambarasan
是的,它是开源的。 - Deepak Rajput
但是这种模糊效果不会影响到边缘。 - c-an

4

也许会有人觉得有用,最新版本 - 只使用 Glide:

-添加到应用 gradle:

implementation("com.github.bumptech.glide:glide:4.9.0") {
    exclude group: "com.android.support"
}
kapt 'com.github.bumptech.glide:compiler:4.9.0'

-在你的布局中:

    <ImageView
    android:id="@+id/ivBlurred"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="centerCrop"
    tools:ignore="ContentDescription" />

在类中,您需要添加您的图像:

 Glide.with(context)
            .asBitmap()
            .load(R.drawable.temp_full_screen_image) // or url
            .transform(BlurTransformation(context))
            .into(ivBlurred)

-最后:

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.renderscript.*
import android.renderscript.RenderScript.RSMessageHandler
import androidx.annotation.ColorInt
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapResource
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import java.security.MessageDigest

private const val DEFAULT_DOWN_SAMPLING = 0.5f

class BlurTransformation(private val context: Context) : BitmapTransformation() {

    override fun transform(pool: BitmapPool, toTransform: Bitmap, outWidth: Int, outHeight: Int): Bitmap? {
        val source: Bitmap = toTransform
        val scaledWidth = (source.width * DEFAULT_DOWN_SAMPLING).toInt()
        val scaledHeight = (source.height * DEFAULT_DOWN_SAMPLING).toInt()
        val bitmap = pool[scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888]
        return BitmapResource.obtain(this.blurBitmap(context, source, bitmap, Color.argb(90, 255, 255, 255)), pool)?.get()
    }

    override fun updateDiskCacheKey(messageDigest: MessageDigest) {
        messageDigest.update("blur transformation".toByteArray())
    }

    @Synchronized
    fun blurBitmap(context: Context, source: Bitmap?, bitmap: Bitmap, @ColorInt colorOverlay: Int): Bitmap? {
        if (source == null) return bitmap
        Canvas(bitmap).apply {
            scale(DEFAULT_DOWN_SAMPLING, DEFAULT_DOWN_SAMPLING)
            drawBitmap(source, 0f, 0f, Paint().apply {
                flags = Paint.FILTER_BITMAP_FLAG
            })
            drawColor(colorOverlay)
        }
        return try {
            blur(context, bitmap)
        } catch (e: RSRuntimeException) {
            e.printStackTrace()
            bitmap
        }
    }

    @Throws(RSRuntimeException::class)
    private fun blur(context: Context, bitmap: Bitmap): Bitmap {
        var rs: RenderScript? = null
        var input: Allocation? = null
        var output: Allocation? = null
        var blur: ScriptIntrinsicBlur? = null
        try {
            rs = RenderScript.create(context)
            rs.messageHandler = RSMessageHandler()
            input = Allocation.createFromBitmap(rs, bitmap, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT)
            output = Allocation.createTyped(rs, input.type)
            blur = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)).apply {
                setInput(input)
                setRadius(25f)
                forEach(output)
            }
            output.copyTo(bitmap)
        } finally {
            rs?.destroy()
            input?.destroy()
            output?.destroy()
            blur?.destroy()
        }
        return bitmap
    }
}

1
很好的答案,但在api31中已被弃用,需要更新。 - Eren Tüfekçi

3
这可能会对你有所帮助。
 Glide.with(context)
    .load(yourUrl)
    .placeholder(yourPlaceholder)
    .override(20,20)
    .into(imageView);

这不会模糊图像,而是覆盖了图像的大小并使其非常像素化。它看起来有点像模糊,但实际上不是。如果您这样做,它会显得非常不专业。 - Robby Lebotha

3
如果你在这个单词下面看到了一条红线:
 .apply(bitmapTransform(new BlurTransformation(22)))

只需添加RequestOptions。
.apply(RequestOptions.bitmapTransform(new BlurTransformation(22)))

1
为什么我会更喜欢这个答案而不是现有的答案?请编辑您的答案并提供解释。 - Jeremy Caney

2

对于Glide V3,

 Glide.with(context).load(imagePath).transform(new BlurTransformation(context))
                                        .into(imageView);

我正在使用这个类来进行模糊转换。
public class BlurTransformation extends BitmapTransformation {

private RenderScript rs;

public BlurTransformation(Context context) {
    super( context );

    rs = RenderScript.create( context );
}

@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
    Bitmap blurredBitmap = toTransform.copy( Bitmap.Config.ARGB_8888, true );

    // Allocate memory for Renderscript to work with
    Allocation input = Allocation.createFromBitmap(
        rs, 
        blurredBitmap, 
        Allocation.MipmapControl.MIPMAP_FULL, 
        Allocation.USAGE_SHARED
    );
    Allocation output = Allocation.createTyped(rs, input.getType());

    // Load up an instance of the specific script that we want to use.
    ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
    script.setInput(input);

    // Set the blur radius
    script.setRadius(10);

    // Start the ScriptIntrinisicBlur
    script.forEach(output);

    // Copy the output to the blurred bitmap
    output.copyTo(blurredBitmap);

    toTransform.recycle();

    return blurredBitmap;
}

@Override
public String getId() {
    return "blur";
}

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接