Android development and learning-How to Implement Dynamic Gaussian blur, android Gaussian

Source: Internet
Author: User

Android development and learning-How to Implement Dynamic Gaussian blur, android Gaussian

What is Gaussian blur?

Gaussian blurGaussian Blur, also known as Gaussian smoothing, is used in Adobe Photoshop, GIMP, and painting. which is widely used in image processing software such as. NET. It is usually used to reduce image noise and the level of detail. The visual effect of an image generated by this fuzzy technique is like watching the image through a translucent screen, which is significantly different from that of an out-of-camera imaging image with scattered scenes and general lighting shadows.

What? Can't you see it? It doesn't matter. I can't understand it either. I copied it back from Wikipedia. Let's put some pictures to see how Gaussian Blur is like. This is because Gaussian Blur is the most common in iOS. Here we capture several pictures of iOS Netease cloud:

We can see that the background in this interface is actually obtained through the blur of the small image in Figure 1. The advantage of doing so is that the integrity is good and it will not affect the reading of the interface content because of the abrupt transition of the image.

So how can this effect be achieved on Android? We recommend that you use a tool officially provided in the Support Library.RenderScript. In fact, this RenderScript has more than one function, while other functions can be read and learned in the official documentation, which is not provided here.

The reason for using this tool is actually very simple, that is, performance. Because drawing is involved, if the performance is not good, it is difficult to meet the needs of high-quality images or a large number of changes, this tool makes full use of the computing power (CPU and GPU) of the device for computing, and uses the C99 derivative language for script writing, which greatly improves the performance compared with Java.

Speaking of this, some of them have started to work out. Is C99 derivative? What? There is no need to worry about this. For the implementation of Gaussian blur, Google has provided the corresponding solution. We don't need to write the corresponding script to use it, so don't worry.

 

We divide the entire problem into two parts: ① Gaussian fuzzy implementation; ② Dynamic Gaussian fuzzy implementation

 

① Gaussian fuzzy implementation

First of all, we need to use the Support Library, so the version is required:

  • Android SDK Tools must be later than or equal to 22.2
  • Android SDK Build-tools must be later than or equal to 18.1.0

If not, use SDK Manager to upgrade.

Create our project and add the following code to the build. gradle file of the corresponding Module (the app is created by default:

defaultConfig {        ...        renderscriptTargetApi 18        renderscriptSupportModeEnabled true    }

RenderscriptTargetApi: This is generally the same as the minimum version supported by the App.

Package com. fndroid. renderscriptdemo; import android. graphics. bitmap; import android. graphics. bitmapFactory; import android. OS. bundle; import android. renderscript. allocation; import android. renderscript. element; import android. renderscript. renderScript; import android. renderscript. scriptIntrinsicBlur; import android. support. v7.app. appCompatActivity; import android. widget. imageView; public class MainActivity extends AppCompatActivity {private ImageView mImageView; private Bitmap sampleImg; private Bitmap gaussianBlurImg; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); mImageView = (ImageView) findViewById (R. id. iv); sampleImg = BitmapFactory. decodeResource (getResources (), R. drawable. icon); // obtain the original image gaussianBlurImg = blur (sampleImg, 25f); mImageView. setImageBitmap (gaussianBlurImg);} private Bitmap blur (Bitmap bitmap, float radius) {Bitmap output = Bitmap. createBitmap (bitmap); // create the output image RenderScript rs = RenderScript. create (this); // construct an RenderScript object ScriptIntrinsicBlur gaussianBlue = ScriptIntrinsicBlur. create (rs, Element. u8_4 (rs); // creates the Gaussian fuzzy script Allocation allIn = Allocation. createFromBitmap (rs, bitmap); // create the input Script Type Allocation allOut = Allocation. createFromBitmap (rs, output); // create the Script Type gaussianBlue for output. setRadius (radius); // set the Blur radius, range: 0f <radius <= 25f gaussianBlue. setInput (allIn); // set the input Script Type gaussianBlue. forEach (allOut); // execute the Gaussian fuzzy algorithm and enter the result in allOut of the output script type. copyTo (output); // encode the output memory as Bitmap. Pay attention to rs for the image size. destroy (); // closes the RenderScript object. rs is used when the API is greater than or equal to 23. releaseAllContexts () return output ;}}

The descriptions are all commented out in the Code. You need to know that RenderScript has two versions:

  • Android. renderscript
  • Android. support. v8.renderscript

The above Code uses the first one, and the second one is similar in usage. You can try it on your own.

Let's take a look at our ideas, because RenderScript relies on scripts, and as mentioned above, scripts are written in C99 derivative languages, the ScriptIntrinsicBlur in the Code is the script corresponding to the Gaussian fuzzy algorithm. The Allocation object is a helper to convert the objects in Java to the types required by the Script. Two Allocation objects are created in the code to act as the input and output respectively. Then the radius is set ). When forEach is called, the script is executed, and the execution result is filled in the corresponding Allocation of the output. Finally, copyTo is called to convert the result to a Bitmap object and return the result.

:

 

② Dynamic Gaussian blur

In many cases, we may need an image to be blurred to varying degrees. You may have noticed the Blur radius in the above method. We can perform an experiment to dynamically change this value through a SeekBar to see the effect:

The animation shows that when we drag the SeekBar, The SeekBar cannot keep up with our drag. Why? The reason is that although the rendering tool has excellent performance, if the image quality and size are high, we can directly modify the Blur radius to re-render the method is often not desirable.

Here is a solution. This Idea comes from Guo Da's author "Xiaoshui Changtian ".

The practice is,First, create a blurred image and load it into the ImageView. Then, place an image attached to the ImageView. FrameLayout can overlap the two imageviews, then, when we need to dynamically change the Blur level, we can change the BitmapAlpha of the Upper-layer ImageView.. Let's take a look:

With this method, it will be smoother to slide. (It will be a normal speed after the GIF is loaded)

Here is a reference to the code:

Public class MainActivity extends AppCompatActivity implements SeekBar. other {private ImageView mImageView; private ImageView mImageViewCover; private Bitmap sampleImg; private Bitmap upload; private SeekBar mSeekBar; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); mImageView = (ImageView) findViewById (R. id. iv); mSeekBar = (SeekBar) findViewById (R. id. sb); mImageViewCover = (ImageView) findViewById (R. id. iv_cover); sampleImg = BitmapFactory. decodeResource (getResources (), R. drawable. icon); // obtain the original image gaussianBlurImg = blur (sampleImg, 25f); mImageView. setImageBitmap (gaussianBlurImg); mSeekBar. setOnSeekBarChangeListener (this);} private Bitmap blur (Bitmap bitmap, float radius) {Bitmap output = Bitmap. createBitmap (bitmap); // create the output image RenderScript rs = RenderScript. create (this); // construct an RenderScript object ScriptIntrinsicBlur gaussianBlue = ScriptIntrinsicBlur. create (rs, Element. u8_4 (rs); // create the Gaussian fuzzy script Allocation allIn = Allocation. createFromBitmap (rs, bitmap); // open the input memory Allocation allOut = Allocation. createFromBitmap (rs, output); // open the output memory gaussianBlue. setRadius (radius); // set the Blur radius, range: 0f <radius <= 25f gaussianBlue. setInput (allIn); // set the input memory gaussianBlue. forEach (allOut); // fuzzy encoding, and fill in the memory with the output memory allOut. copyTo (output); // encode the output memory as Bitmap. Pay attention to rs for the image size. destroy (); // closes the RenderScript object. rs is used when the API is greater than or equal to 23. releaseAllContexts () return output;} @ Override public void onProgressChanged (SeekBar seekBar, int progress, boolean fromUser) {int alpha = 255-progress; mImageViewCover. setImageAlpha (alpha) ;}@ Override public void onStartTrackingTouch (SeekBar seekBar) {}@ Override public void onStopTrackingTouch (SeekBar seekBar ){}}

Layout file:

<?xml version="1.0" encoding="utf-8"?><LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.fndroid.renderscriptdemo.MainActivity">    <FrameLayout        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1">        <ImageView            android:id="@+id/iv"            android:layout_width="match_parent"            android:layout_height="match_parent"/>        <ImageView            android:id="@+id/iv_cover"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:src="@drawable/icon"/>    </FrameLayout>    <SeekBar        android:id="@+id/sb"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:max="255"/></LinearLayout>

 

If any error is found, please point out and thank you.

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.