如何在android中模糊imageview

时间:2015-01-08 01:33:01

标签: android

我有一个imageview,我以编程方式设置Image Resources:

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

有没有简单的方法来显示我的ImageView模糊图像?

13 个答案:

答案 0 :(得分:12)

这个项目显然使图像变得模糊。这个对我有用。 https://github.com/Cutta/Simple-Image-Blur

答案 1 :(得分:5)

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

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

答案 2 :(得分: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 :(得分:2)

有许多可用的库,您可以使用其中的任何一个。 我更喜欢 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 :(得分:1)

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 :(得分:0)

您可以使用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());

答案 6 :(得分:0)

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

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

答案 7 :(得分:0)

在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.

答案 8 :(得分:0)

添加依赖项

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 :(得分:0)

只需使用此库https://github.com/ChathuraHettiarachchi/BlurIM ,我在BlurTransformation类上遇到了一个错误,那就是为什么不能使用Glide转换,但这还是可以的。

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

答案 10 :(得分:0)

您还可以使用 Coil 库对 ImageView 进行模糊处理。

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

答案 11 :(得分:0)

原回答here

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

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

答案 12 :(得分:-2)

这是一种简单的方法

使用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);
    }
}