Skip to content

Instantly share code, notes, and snippets.

@imminent
Last active August 29, 2015 14:11
Show Gist options
  • Save imminent/cf4ab750104aa286fa08 to your computer and use it in GitHub Desktop.
Save imminent/cf4ab750104aa286fa08 to your computer and use it in GitHub Desktop.
Invert and Grayscale Transformation using RenderScript
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