Home | History | Annotate | Download | only in common
      1 /*
      2  * Copyright 2018 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.android.car.apps.common;
     18 
     19 import android.annotation.NonNull;
     20 import android.content.Context;
     21 import android.graphics.Bitmap;
     22 import android.renderscript.Allocation;
     23 import android.renderscript.Element;
     24 import android.renderscript.RenderScript;
     25 import android.renderscript.ScriptIntrinsicBlur;
     26 
     27 /**
     28  * Utility methods to manipulate images.
     29  */
     30 public class ImageUtils {
     31     /**
     32      * Blurs the given image by scaling it down by the given factor and applying the given
     33      * blurring radius.
     34      */
     35     @NonNull
     36     public static Bitmap blur(Context context, @NonNull Bitmap image, float scale, float radius) {
     37         int width = Math.round(image.getWidth() * scale);
     38         int height = Math.round(image.getHeight() * scale);
     39 
     40         if (image.getConfig() != Bitmap.Config.ARGB_8888) {
     41             image = image.copy(Bitmap.Config.ARGB_8888, true);
     42         }
     43 
     44         Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
     45         Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
     46 
     47         RenderScript rs = RenderScript.create(context);
     48         ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
     49         Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
     50         Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
     51         theIntrinsic.setRadius(radius);
     52         theIntrinsic.setInput(tmpIn);
     53         theIntrinsic.forEach(tmpOut);
     54         tmpOut.copyTo(outputBitmap);
     55 
     56         return outputBitmap;
     57     }
     58 }
     59