Как размыть изображение в андроиде

У меня есть изображение и я устанавливаю Image Resources программно следующим образом:

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

Есть ли какой-нибудь простой способ показать мой ImageView с размытым изображением?

Ответы

Ответ 2

Вы можете использовать глиссирование https://github.com/wasabeef/glide-transformations, вы можете размыть изображение одной строкой кода

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

Ответ 3

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

Ответ 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>

нажмите здесь приведенный код кода

Ответ 5

Вы можете использовать RenderScript, чтобы узнать, как описано здесь или вы можете использовать библиотеку 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

Там библиотека, которая может использовать RenderScript, чтобы размытие было невероятно быстрым и супер простым в использовании:

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

Ответ 7

Есть разные способы сделать размытие изображения в android, но я нашел самый простой и быстрый способ сделать размытие просмотров, используя библиотеку Fresco.

Добавьте следующую зависимость внутри вашего build.gradle вашего модуля.

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

И внутри onCreate() Activity.

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

Если вам нужна полная реализация, посетите этот блог Самое быстрое размытие изображения в Android с помощью Fresco.

Ответ 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

Просто используйте эту библиотеку https://github.com/ChathuraHettiarachchi/BlurIM, у меня были проблемы с классом BlurTransformation, были ошибки, поэтому я не мог использовать преобразование Glide, но это прекрасно работает.

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

Ответ 10

Это простой метод

установить цвет размытия с альфа

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