Skip to content

Instantly share code, notes, and snippets.

@mebjas
Created July 6, 2021 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mebjas/f639adec844f4046ffba0f9c4f614291 to your computer and use it in GitHub Desktop.
Save mebjas/f639adec844f4046ffba0f9c4f614291 to your computer and use it in GitHub Desktop.
YUV to ARGB Bitmap using Renderscript
static Bitmap yuv420ToBitmap(Image image, Context context) {
RenderScript rs = RenderScript.create(context);
ScriptIntrinsicYuvToRGB script = ScriptIntrinsicYuvToRGB.create(
rs, Element.U8_4(rs));
// Refer the logic in a section below on how to convert a YUV_420_888 image
// to single channel flat 1D array. For sake of this example I'll abstract it
// as a method.
byte[] yuvByteArray = yuv420ToByteArray(image);
Type.Builder yuvType = new Type.Builder(rs, Element.U8(rs))
.setX(yuvByteArray.length);
Allocation in = Allocation.createTyped(
rs, yuvType.create(), Allocation.USAGE_SCRIPT);
Type.Builder rgbaType = new Type.Builder(rs, Element.RGBA_8888(rs))
.setX(image.getWidth())
.setY(image.getHeight());
Allocation out = Allocation.createTyped(
rs, rgbaType.create(), Allocation.USAGE_SCRIPT);
// The allocations above "should" be cached if you are going to perform
// repeated conversion of YUV_420_888 to Bitmap.
in.copyFrom(yuvByteArray);
script.setInput(in);
script.forEach(out);
Bitmap bitmap = Bitmap.createBitmap(
image.getWidth(), image.getHeight(), Config.ARGB_8888);
out.copyTo(bitmap);
return bitmap;
}
@MasterHansCoding
Copy link

How yuv420ToByteArray() should be ?

@MrCsabaToth
Copy link

Where is the yuv420ToByteArray?

@mebjas
Copy link
Author

mebjas commented Jan 24, 2023

@MrCsabaToth
Copy link

@mebjas Thanks, the snippet you pointed to is toYuvImage which converts a Media.Image into YuvImage. Wherever you grabbed the snippet above (and it's also in the article I found earlier) - could you open up that source repository, search for that specific function and add that to the Gist too?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment