Last active
August 29, 2015 14:11
-
-
Save imminent/cf4ab750104aa286fa08 to your computer and use it in GitHub Desktop.
Invert and Grayscale Transformation using RenderScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package your.package; | |
import android.content.Context; | |
import android.graphics.Bitmap; | |
import android.support.v8.renderscript.Allocation; | |
import android.support.v8.renderscript.Element; | |
import android.support.v8.renderscript.Matrix4f; | |
import android.support.v8.renderscript.RenderScript; | |
import android.support.v8.renderscript.ScriptIntrinsicColorMatrix; | |
import com.squareup.picasso.Transformation; | |
class InvertAndGrayscaleTransformation implements Transformation { | |
private static final Matrix4f TRANSFORMATION_MATRIX = new Matrix4f(new float[] | |
{ | |
-0.33f, -0.33f, -0.33f, 1.0f, | |
-0.59f, -0.59f, -0.59f, 1.0f, | |
-0.11f, -0.11f, -0.11f, 1.0f, | |
1.0f, 1.0f, 1.0f, 1.0f | |
}); | |
private final RenderScript mRender; | |
public InvertAndGrayscaleTransformation(Context context) { | |
mRender = RenderScript.create(context); | |
} | |
@Override | |
public Bitmap transform(Bitmap source) { | |
final Bitmap result = source.copy(source.getConfig(), true); | |
Allocation input = Allocation.createFromBitmap(mRender, source, | |
Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT); | |
Allocation output = Allocation.createTyped(mRender, input.getType()); | |
// Inverts and grayscales the image | |
final ScriptIntrinsicColorMatrix inverter = ScriptIntrinsicColorMatrix.create(mRender, Element.U8_4(mRender)); | |
inverter.setColorMatrix(TRANSFORMATION_MATRIX); | |
inverter.forEach(input, output); | |
output.copyTo(result); | |
source.recycle(); | |
mRender.destroy(); | |
return result; | |
} | |
@Override | |
public String key() { | |
return "invertAndGrayscale()"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment