The realization of Gaussian blur _android with Android Renderscript

Source: Internet
Author: User
Tags float max

Yesterday read the official document of Renderscript, found that renderscript this fellow is a bit of a kick. Accidentally found Scriptintrinsic this abstract class, some very useful subclasses. One of them is called the Scriptintrinsicblur class, which is basically the image to achieve a Gaussian blur.

Scriptintrinsic's statement:

Scriptintrinsicblur the declaration of the class:

Coupled with a look at the next SDK in the samples, he wrote a Gaussian blur.
(The exact location of sample is:
SDK Directory/samples/android-19/renderscript/renderscriptintrinsic/renderscriptintrinsicsample/
)。

First figure. The effect is as follows:

"Attention!! Before we start, we need to import the required support packs.
The specific path to the support package is: SDK directory/buildtools/any version number/renderscript/lib/renderscript-v8.jar
In addition: In order to prevent the emergence of a model compatibility problem, it is best to renderscript-v8.jar the same directory under the packaged directory of all libraries are also copied to the Lib folder.

For example:

All right. Start writing code.

1. Declare the common member variable first.

Private SeekBar blurseekbar;//Drag bar
private ImageView img_blur;//show blur bitmap ImageView
// The original Bitmap and Gauss Fuzzy Bitmap
private Bitmap bitmap_original, Bitmap_blur;
Gauss fuzzy processing asynctask
private renderscripttask mlatesttask = null;
Renderscript object (Google's High-performance parallel computing class, he can use equipment such as GPU/CPU computing resources)
private renderscript MRS;
Here are two renderscript incoming parameter objects
private allocation minallocation;
private allocation moutallocation;
Gaussian fuzzy processing instance
private Scriptintrinsicblur Mscriptblur;

2, loading two copies of bitmap, and initializing Gaussian blur related objects.

@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.activity_main);
  Blurseekbar = (SeekBar) Findviewbyid (R.id.aty_main_seekbar);

  Img_blur = (ImageView) Findviewbyid (R.id.aty_main_img_blur);
  Bitmap_original = LoadBitmap (r.drawable.meet_entry_guide_3); Copies a copy of Bitmap_blur = Bitmap.createbitmap (Bitmap_original.getwidth (), Bitmap_original.getheight (), bitmap_original
  . GetConfig ());
  Createblurescript (); Setseekbarlistening ()///For Seekbar settings drag-and-drop listening}/** * Helper to load Bitmap from resource/private Bitmap LoadBitmap (int res
  Ource) {final bitmapfactory.options Options = new Bitmapfactory.options ();
  Options.inpreferredconfig = Bitmap.Config.ARGB_8888;
Return Bitmapfactory.decoderesource (Getresources (), Resource, options);
  /** * Create script/private void Createblurescript () {MRS = Renderscript.create (this);
  Minallocation = Allocation.createfrombitmap (MRS, bitmap_original); Moutallocation = Allocation.createfrombitmap (MRS, Bitmap_blur); * * Create intrinsics. Renderscript has built-in features such as Blur, * convolve filter etc. These intrinsics are handy for specific * operations without writing renderscript.
   In the sample, it ' s * creating blur, Convolve and Matrix intrinsics.
* * Mscriptblur = scriptintrinsicblur.create (Mrs, Element.u8_4 (Mrs));

 }

3, the completion of the Gauss Fuzzy processing code.

private void Performfilter (allocation inallocation,
      allocation outallocation, Bitmap bitmapout, float value) {
   * * Set the degree of ambiguity. Range between the 0~25. Otherwise there will be an error
   * *
  Mscriptblur.setradius (value);
   * * Invoke Filter Kernel * *
  mscriptblur.setinput (inallocation);
  Mscriptblur.foreach (outallocation);

  Outallocation.copyto (bitmapout);
}

4, the processing of the bitmap set to the ImageView.

Request UI update
img_blur.setimagebitmap (bitmap_blur);
Img_blur.invalidate ();

The basic work is done. The rest is the code calling each other.

Summary
in fact, the use of renderscript for Gaussian Blur is mainly divided into three steps:

1. Create and initialize the objects you need (once initialization is OK).

MRS = Renderscript.create (this);
Mscriptblur = Scriptintrinsicblur.create (Mrs, Element.u8_4 (Mrs));
Renderscript input and output parameter object
minallocation = Allocation.createfrombitmap (MRS, bitmap_original);
Moutallocation = Allocation.createfrombitmap (MRS, Bitmap_blur);

2, the implementation of Gaussian blur, and copy the results.


 * * Set the degree of ambiguity. Range between the 0~25. Otherwise there will be an error (this can be set only once)/
Mscriptblur.setradius (value);
 * * Invoke Filter Kernel * *
mscriptblur.setinput (inallocation);
Mscriptblur.foreach (outallocation);
Copy the results and copy them to the Bitmapout object
outallocation.copyto (bitmapout);

3, Recycling Renderscript objects

Mrs.destory ();
MRs = null; 

The article ends here.

By convention: Here is my complete code implementation.

public class Mainactivity extends activity {private SeekBar Blurseekbar;
  Private ImageView Img_blur;

  Private Bitmap bitmap_original, Bitmap_blur;

  Private Renderscripttask mlatesttask = null;
  Private Renderscript MRS;
  private allocation minallocation;
  private allocation moutallocation;

  Private Scriptintrinsicblur Mscriptblur;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
    Blurseekbar = (SeekBar) Findviewbyid (R.id.aty_main_seekbar);
    Img_blur = (ImageView) Findviewbyid (R.id.aty_main_img_blur);
    Bitmap_original = LoadBitmap (r.drawable.meet_entry_guide_3); Copies a copy of Bitmap_blur = Bitmap.createbitmap (Bitmap_original.getwidth (), Bitmap_original.getheight (), Bitmap_orig
    Inal.getconfig ());
    Createblurescript ();
  Setseekbarlistening (); /** * Set Seekbar monitor/private void setseekbarlistening () {Blurseekbar.setonseekbarchangeListener (New Onseekbarchangelistener () {@Override public void Onstoptrackingtouch (SeekBar SeekBar) {} @Override public void Onstarttrackingtouch (SeekBar SeekBar) {} @Override public void on
      ProgressChanged (SeekBar SeekBar, int progress, Boolean fromuser) {updateimage (progress);
  }
    });
    /** * Create script/private void Createblurescript () {MRS = Renderscript.create (this);
    Minallocation = Allocation.createfrombitmap (MRS, bitmap_original);

    Moutallocation = Allocation.createfrombitmap (MRS, Bitmap_blur); * * Create intrinsics. Renderscript has built-in features such as Blur, * convolve filter etc. These intrinsics are handy for specific * operations without writing renderscript.
     In the sample, it ' s * creating blur, Convolve and Matrix intrinsics.
  * * Mscriptblur = scriptintrinsicblur.create (Mrs, Element.u8_4 (Mrs)); } private void Performfilter (allocation inallocation, allocation outallocation, Bitmap bitmapout, float value) {/* * Set Blur Kerne

    L Size */Mscriptblur.setradius (value);
    * * Invoke Filter Kernel * * Mscriptblur.setinput (inallocation);

    Mscriptblur.foreach (outallocation);
  Outallocation.copyto (bitmapout);
   } * * In the Asynctask, it invokes Renderscript intrinsics to do a filtering. * After the filtering was done, a operation blocks at Allication.copyto () * in Asynctask thread.
   Once all operation are finished at OnPostExecute () in * UI thread, it can invalidate and update ImageView UI.

    * * Private class Renderscripttask extends Asynctask<float, Integer, integer> {Boolean issued = false;
        Protected Integer doinbackground (Float ... values) {if (iscancelled () = = False) {issued = true;
      Performfilter (Minallocation, Moutallocation, Bitmap_blur, values[0]);
    return 0; } void UPdateview (Integer result) {//Request UI update Img_blur.setimagebitmap (Bitmap_blur);
    Img_blur.invalidate ();
    } protected void OnPostExecute (Integer result) {Updateview (result);
      } protected void oncancelled (Integer result) {if (issued) {Updateview (result); }}/* Invoke Asynchtask and cancel previous task.  When asynctasks are piled up * (typically in slow device with heavy kernel), only the latest (and * already started)
   Task invokes Renderscript operation.

    * * private void UpdateImage (int progress) {float F = getblureparam (progress);
    if (mlatesttask!= null) Mlatesttask.cancel (FALSE);
    Mlatesttask = new Renderscripttask ();
  Mlatesttask.execute (f); /** * Fuzzy value between 1 ~ 25 * * @param progress * Seekbar Progress value (0 ~) * @return Fuzzy value/Private Flo
    at Getblureparam (int progress) {final float max = 25.0f;
    Final float min = 1.f; Return (float) ((max-min) * (progress/100.0) + min); }/** * Helper to load Bitmap from resource/private Bitmap LoadBitmap (int resource) {final bitmapfactor
    Y.options Options = new Bitmapfactory.options ();
    Options.inpreferredconfig = Bitmap.Config.ARGB_8888;
  Return Bitmapfactory.decoderesource (Getresources (), Resource, options);

 }
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.