【问题标题】:How to blur imageview in android如何在android中模糊imageview
【发布时间】:2019-10-30 20:03:41
【问题描述】:

我有一个 imageview,我像这样以编程方式设置图像资源:

int resourceId = getResources().getIdentifier("imagename", "drawable", "mypackage");
imgLock.setImageResource(resourceId);

有什么简单的方法可以用模糊的图像显示我的 ImageView 吗?

【问题讨论】:

  • 它给了我NullPointerExceptionBitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
  • 请看我的回答,这绝对可以解决您的问题

标签: android


【解决方案1】:

您可以使用滑行变换 https://github.com/wasabeef/glide-transformations 你可以用一行代码模糊图像

Glide.with(this).load(R.drawable.demo)
    .bitmapTransform(new BlurTransformation(context))
    .into((ImageView) findViewById(R.id.image));

【讨论】:

    【解决方案2】:
    import android.renderscript.Allocation;
    import android.renderscript.Element;
    import android.renderscript.RenderScript;
    import android.renderscript.ScriptIntrinsicBlur;
    
    Bitmap blurred = blurRenderScript(this,yourBitmap, 25);
    //second parametre is radius
    yourImageView.setImageBitmap(blurred); 
    
    @SuppressLint("NewApi")
    public static Bitmap blurRenderScript(Context context,Bitmap smallBitmap, int radius) {
    try {
            smallBitmap = RGB565toARGB888(smallBitmap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        Bitmap bitmap = Bitmap.createBitmap(
                smallBitmap.getWidth(), smallBitmap.getHeight(),
                Bitmap.Config.ARGB_8888);
    
        RenderScript renderScript = RenderScript.create(context);
    
        Allocation blurInput = Allocation.createFromBitmap(renderScript, smallBitmap);
        Allocation blurOutput = Allocation.createFromBitmap(renderScript, bitmap);
    
        ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(renderScript,
                Element.U8_4(renderScript));
        blur.setInput(blurInput);
        blur.setRadius(radius); // radius must be 0 < r <= 25
        blur.forEach(blurOutput);
    
        blurOutput.copyTo(bitmap);
        renderScript.destroy();
    
        return bitmap;
    }
    
    private static Bitmap RGB565toARGB888(Bitmap img) throws Exception {
        int numPixels = img.getWidth() * img.getHeight();
        int[] pixels = new int[numPixels];
    
        //Get JPEG pixels.  Each int is the color values for one pixel.
        img.getPixels(pixels, 0, img.getWidth(), 0, 0, img.getWidth(), img.getHeight());
    
        //Create a Bitmap of the appropriate format.
        Bitmap result = Bitmap.createBitmap(img.getWidth(), img.getHeight(), Bitmap.Config.ARGB_8888);
    
        //Set RGB pixels.
        result.setPixels(pixels, 0, result.getWidth(), 0, 0, result.getWidth(), result.getHeight());
        return result;
    }
    

    【讨论】:

    【解决方案3】:

    有许多可用的库,您可以使用其中的任何一个。 我更喜欢Blurry 库。 它非常简单且经过优化。

    依赖:

     dependencies {
        compile 'jp.wasabeef:blurry:4.x.x'
    }
    

    函数

    • Blurry.with(context).radius(25).sampling(2).onto(rootView)
    • // from View Blurry.with(context).capture(view).into(imageView)
    • // from Bitmap Blurry.with(context).from(bitmap).into(imageView)

    模糊选项

    • 半径
    • 下采样
    • 彩色滤光片
    • 异步支持
    • 动画(仅覆盖)
    Blurry.with(context)
      .radius(10)
      .sampling(8)
      .color(Color.argb(66, 255, 255, 0))
      .async()
      .animate(500)
      .onto(rootView);
    

    直接获取位图

    // Sync
    val bitmap = Blurry.with(this)
      .radius(10)
      .sampling(8)
      .capture(findViewById(R.id.right_bottom)).get()
    imageView.setImageDrawable(BitmapDrawable(resources, bitmap))
    
    // Async
    Blurry.with(this)
      .radius(25)
      .sampling(4)
      .color(Color.argb(66, 255, 255, 0))
      .capture(findViewById(R.id.left_bottom))
      .getAsync {
        imageView.setImageDrawable(BitmapDrawable(resources, it))
      }
    

    【讨论】:

      【解决方案4】:
      private Bitmap CreateBlurredImage (int radius)
      {
         // Load a clean bitmap and work from that
          Bitmap originalBitmap=
          BitmapFactory.DecodeResource(Resources,Resource.Drawable.dog_and_monkeys);
      
      // Create another bitmap that will hold the results of the filter.
      Bitmap blurredBitmap;
      blurredBitmap = Bitmap.CreateBitmap (originalBitmap);
      
      // Create the Renderscript instance that will do the work.
      RenderScript rs = RenderScript.Create (this);
      
      // Allocate memory for Renderscript to work with
      Allocation input = Allocation.CreateFromBitmap (rs, originalBitmap, Allocation.MipmapControl.MipmapFull, AllocationUsage.Script);
      Allocation output = Allocation.CreateTyped (rs, input.Type);
      
      // 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 (radius);
      
      // Start the ScriptIntrinisicBlur
      script.ForEach (output);
      
      // Copy the output to the blurred bitmap
      output.CopyTo (blurredBitmap);
      
      return blurredBitmap;
      

      }

      protected override void OnCreate (Bundle bundle)
      {
      base.OnCreate (bundle);
      
      SetContentView (Resource.Layout.Main);
      _imageView = FindViewById<ImageView> (Resource.Id.originalImageView);
      
      _seekbar = FindViewById<SeekBar> (Resource.Id.seekBar1);
      _seekbar.StopTrackingTouch += BlurImageHandler;
      

      }

      private void BlurImageHandler (object sender, SeekBar.StopTrackingTouchEventArgs e)
      {
      int radius = e.SeekBar.Progress;
      if (radius == 0) {
          // We don't want to blur, so just load the un-altered image.
          _imageView.SetImageResource (Resource.Drawable.dog_and_monkeys);
      } else {
          DisplayBlurredImage (radius);
      }
      

      }

      private void DisplayBlurredImage (int radius)
      {
      _seekbar.StopTrackingTouch -= BlurImageHandler;
      _seekbar.Enabled = false;
      
      ShowIndeterminateProgressDialog ();
      
      Task.Factory.StartNew (() => {
          Bitmap bmp = CreateBlurredImage (radius);
          return bmp;
      })
      .ContinueWith (task => {
          Bitmap bmp = task.Result;
          _imageView.SetImageBitmap (bmp);
          _seekbar.StopTrackingTouch += BlurImageHandler;
          _seekbar.Enabled = true;
          DismissIndeterminateProgressDialog ();
      }, TaskScheduler.FromCurrentSynchronizationContext ());
      

      }

      <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:orientation="vertical"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent">
          <SeekBar
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:id="@+id/seekBar1"
                  android:max="25" />
          <ImageView
                  android:src="@drawable/dog_and_monkeys"
                  android:layout_width="fill_parent"
                  android:layout_height="fill_parent"
                  android:id="@+id/originalImageView" />
      </LinearLayout>
      

      click here deatiled code example

      【讨论】:

        【解决方案5】:

        只需使用这个库https://github.com/ChathuraHettiarachchi/BlurIM ,我遇到了 BlurTransformation 类的问题,有错误,这就是为什么不能使用 Glide 转换,但这工作正常。

        BlurImage.withContext(this)
             .blurFromResource(R.drawable.YOUR_RESOURCE)
             .into(imageView);
        

        【讨论】:

          【解决方案6】:

          您可以使用RenderScript 来完善它,如here 解释的那样,或者您可以使用stackblur 库在您的图像中制作模糊效果。

          stackblur库的使用:

          int resourceId = getResources().getIdentifier("imagename", "drawable", "mypackage");
          // get bitmap from resource id
          Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resourceId);
          StackBlurManager stackBlurManager = new StackBlurManager(bitmap);
          // process the image using a certain radius
          stackBlurManager.process(progress*4);
          // obtain the image and load it into an ImageView or any other component
          imgLock.setImageBitmap(stackBlurManager.returnBlurredImage());
          

          【讨论】:

          • 当我导入 StackBlur 项目时,eclipse 给我这个错误Unable to resolve sdk.buildtools property value '18.1.0' - Unknown Android Build Tools Problem。我该如何解决?
          • 您可以从 Android SDK Manager 安装它。在Tools 部分,您会发现Android Build Tools 只需安装18.1.0 版本。
          • 我安装了,但现在出现新错误RenderScript support mode requires Build-Tools 19.0.3 or later.
          • 似乎是 lib github.com/kikoso/android-stackblur/issues/22 中的一个问题。您应该将 Android 构建工具更改为最新版本。
          【解决方案7】:

          the library 可以使用 RenderScript,因此模糊非常快速且超级易于使用:

          <ru.egslava.blurredview.BlurredImageView
              ...
              android:src="@drawable/..."
              app:radius="0.3"
              app:keepOriginal="true"
              app:downSampling="2" />
          

          【讨论】:

            【解决方案8】:

            添加依赖项

            compile 'jp.wasabeef:fresco-processors:2.1.0'
            

            在布局文件中使用以下代码:

            <com.facebook.drawee.view.SimpleDraweeView
               android:id="@+id/imageView"
               android:layout_width="match_parent"
               android:layout_height="match_parent"/>
            

            在您的 java 文件中使用以下代码:

            SimpleDraweeView imgView = (SimpleDraweeView) findViewById(R.id.imageView);
                        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                                .setPostprocessor(new IterativeBoxBlurPostProcessor(20))
                                .build();
                        DraweeController controller = Fresco.newDraweeControllerBuilder()
                                .setImageRequest(request)
                                .setOldController(imgView.getController())
                                .build();
                        imgView.setController(controller);
            

            【讨论】:

              【解决方案9】:

              您还可以使用 Coil 库来模糊 ImageView。

              image.load("http://xxx.jpg") {
                transformations(BlurTransformation(applicationContext,20f))
              }
              

              【讨论】:

                【解决方案10】:

                原回答here

                Android 12 Preview 1 带有内置的模糊功能。我们现在不需要依赖外部库。这是代码

                imageView.setRenderEffect(
                        RenderEffect.createBlurEffect(
                            20.0f, 20.0f, SHADER_TITLE_MODE
                        )
                )
                

                【讨论】:

                  【解决方案11】:

                  迟到了,但我在加载后尝试直接使用 bitmaptransfrom 时出错。如果您面临同样的问题,请使用:

                  Glide.with(mContext).load(drawable).apply(RequestOptions.bitmapTransform(new BlurTransformation())).into(imageView);
                  

                  【讨论】:

                    【解决方案12】:

                    在 android 中有多种方法可以使视图模糊,但我发现使用 Fresco 库使视图模糊的最简单和最快的方法。

                    在模块的 build.gradle 中添加以下依赖项。

                       compile 'jp.wasabeef:fresco-processors:2.1.0'
                    

                    在 Activity 的 onCreate() 内部。

                            Fresco.initialize(this);
                        setContentView(R.layout.activity_main);
                    
                        SimpleDraweeView  simpleDraweeView = (SimpleDraweeView) findViewById(R.id.sdv_image);
                    
                        //INSTANTIATE BLUR POST PROCESSOR
                        Postprocessor  postprocessor = new BlurPostprocessor(this, BLUR_PRECENTAGE);
                    
                        //INSTATNTING IMAGE REQUEST USING POST PROCESSOR AS PARAMETER
                        ImageRequest  imageRequest = ImageRequestBuilder.newBuilderWithSource(Uri.parse(IMAGE_URL))
                                .setPostprocessor(postprocessor)
                                .build();
                    
                        //INSTANTATE CONTROLLOR()
                        PipelineDraweeController  controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
                                .setImageRequest(imageRequest)
                                .setOldController(simpleDraweeView.getController())
                                .build();
                    
                        //LOAD BLURRED IMAGE ON SimpleDraweeView(VIEW)
                        simpleDraweeView.setController(controller);
                    

                    如果您需要完整的实施,请访问此博客 Fastest Image Blur in Android Using Fresco.

                    【讨论】:

                      【解决方案13】:

                      这个方法很简单

                      使用 alpha 设置模糊颜色

                      public class BlurImageView extends ImageView {
                          Paint rectPaint;
                      
                        private  int blurcolor=Color.parseColor("#aeffffff");
                          public BlurImageView(Context context) {
                              this(context, null);
                      
                          }
                      
                          public BlurImageView(Context context, AttributeSet attrs) {
                              this(context, attrs, 0);
                      
                          }
                      
                          public BlurImageView(Context context, AttributeSet attrs, int defStyleAttr) {
                              super(context, attrs, defStyleAttr);
                      
                              rectPaint=new Paint();
                              rectPaint.setAntiAlias(true);
                              rectPaint.setStyle(Paint.Style.FILL);
                              rectPaint.setColor(blurcolor);
                              invalidate();
                          }
                      
                          public void setBlurcolor(int blurcolor) {
                              this.blurcolor = blurcolor;
                              invalidate();
                          }
                      
                          @Override
                          protected void onDraw(Canvas canvas) {
                              super.onDraw(canvas);
                      
                              Log.i("BlurImageView","canvas");
                      
                              canvas.drawRect(getLeft(),0,getRight(),getHeight(),rectPaint);
                          }
                      }
                      

                      【讨论】:

                      • 这只会在图像视图上添加一个叠加层。模糊不是覆盖。
                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 2014-09-09
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2013-01-11
                      • 2014-03-07
                      相关资源
                      最近更新 更多