How to Convert NV21 to RGB in Java and View Raw YUV Frames
NV21 is the pixel format an Android camera hands you by default, and it has no header. Java can turn it into a viewable image in a few dozen lines: read the luma plane from the first width * height bytes, read the interleaved V/U pairs from the tail, and apply a fixed-point YUV to RGB matrix. The hard part is not the matrix. It is knowing the width, height and chroma order before you touch the buffer.

What you’ll build: a drag-and-drop Java Swing viewer that opens a headerless .yuv file, works out the frame size and pixel layout from the file name, converts NV21, NV12, I420, YV12, I444, YV24, NV16, NV61, YUY2, UYVY, YVYU or Y800 to RGB, and exports the result as PNG. It uses nothing but the JDK and compiles with a single javac command.
Key Takeaways
- NV21 and NV12 store exactly the same 4:2:0 data; only the order of the two chroma bytes differs. Reading them in the wrong order turns skin tones blue, which is the single most common “my decoder is broken” report.
- One 4:2:0 frame is
width * height * 3 / 2bytes, a packed 4:2:2 frame iswidth * height * 2, and a 4:4:4 frame iswidth * height * 3. Comparing that number with the file size tells you whether the settings can be right before you render a single pixel. - Integer coefficients with eight fractional bits (
298is1.164 * 256) plus five 256-entry lookup tables remove all floating point work from the pixel loop, so a 2048 × 1536 frame renders in about 40 ms once the JIT has warmed up. - Writing RGB values directly into the
int[]behindBufferedImage.TYPE_INT_RGBremoves one bounds-checkedsetRGBcall per pixel, which is the difference between a preview that updates as you type and one that stutters. - File names such as
1920x1080_nv12.yuvalready describe the frame. Parsing them removes almost all of the manual setup that raw YUV normally requires.
Common Developer Questions
How do I convert NV21 to RGB in Java?
Read the luma byte from the first width * height bytes of the buffer, read the shared V and U bytes from the interleaved chroma tail, then apply the BT.601 matrix with integer arithmetic: R = (298 * (Y - 16) + 409 * (V - 128)) >> 8. In this sample that logic lives in YuvRenderer, which writes the result straight into a BufferedImage and is driven by a Swing window instead of a hard-coded file name.
What is the difference between NV21 and NV12?
Both are 4:2:0 semi-planar layouts: a full luma plane, then a single interleaved chroma plane holding one V/U pair for every 2 × 2 block of pixels. NV21 stores each pair as V U and NV12 stores it as U V. Android cameras output NV21; iOS and most desktop capture tools output NV12. The viewer exposes the choice as a single combo box entry because nothing else differs between the two decoders.
How do I know the width and height of a .yuv file?
There is no way to read it from the file, because raw YUV has no header. The byte count narrows things down but does not settle it: 3,110,400 bytes is one 1920 × 1080 4:2:0 frame, or one 1280 × 810 4:4:4 frame, or two 1280 × 810 4:2:0 frames. The practical options are to keep the convention in the file name (frame_1920x1080_nv12.yuv), to write the size next to the dump when it is produced, or to try the common resolutions and keep the one whose frame size divides the file evenly. This sample does the first and the third: an explicit name always wins, and the resolution list is only consulted when the name is silent.
Can Java display a raw YUV frame without converting it to RGB?
No. Swing paints BufferedImage objects, and every BufferedImage type is RGB or grayscale based. Java2D does not accept a YUV raster, so a conversion step is unavoidable; the goal is only to make it fast enough to re-run on every settings change, which the lookup-table renderer in this sample does in tens of milliseconds per frame.
How do I save the converted frame as a PNG in Java?
Call ImageIO.write(image, "png", file) on the BufferedImage you already rendered. The JDK ships a PNG writer, a JPEG writer and a GIF writer, but no BMP writer, so a true BMP export still needs a hand-written header.
Prerequisites
- JDK 17 or newer. The code uses records, switch expressions and pattern matching for
instanceof. - Git, to clone the sample.
- A raw YUV file to look at.
Any camera dump works. You can also produce one with FFmpeg:
ffmpeg -i input.mp4 -frames:v 1 -vf scale=1280:720 -pix_fmt nv21 -f rawvideo frame_1280x720_nv21.yuv
The resulting file is 1,382,400 bytes, which is 1280 * 720 * 1.5, and the name already tells the viewer everything it needs.
Step 1: Read the NV21 Memory Layout
An NV21 frame is two planes. The luma plane holds one byte per pixel. The chroma plane holds one V/U pair for every 2 × 2 group of pixels, so it has width * height / 4 pairs — half as many bytes as the luma plane:
luma plane: width * height bytes Y Y Y Y ... Y Y
chroma plane: width * height / 2 bytes V U V U ... V U
For a 2 × 2 group of pixels you get four Y samples and one V and one U sample:
YYYYYYYY VUVU
The chroma plane is laid out row by row like the luma plane, which is the detail that breaks naive decoders. The byte offset of the pair that serves pixel (x, y) is width * height + (y / 2) * width + (x / 2) * 2, not width * height + (y * width) / 2 + x, because a chroma row still spans width bytes even though it only carries width / 2 pairs.
Step 2: Convert YUV to RGB with Fixed-Point Arithmetic
The BT.601 matrix converts limited-range YUV to RGB. Multiplying every coefficient by 256 turns the whole formula into integer work, and the + 128 before the shift rounds instead of truncating:
int base = (y - 16) * 298; // 298 = 1.164 * 256
int r = (base + 409 * (v - 128) + 128) >> 8;
int g = (base - 100 * (u - 128) - 208 * (v - 128) + 128) >> 8;
int b = (base + 516 * (u - 128) + 128) >> 8;
Two details matter for correctness. First, y must be an unsigned byte: data[i] & 0xFF, otherwise every value above 127 becomes negative. Second, the result has to be clamped to [0, 255]; the matrix overshoots on saturated colors.
Computing those products per pixel is wasteful when there are only 256 possible inputs per channel, so the renderer builds five lookup tables once per frame:
private Lut(ColorStandard standard) {
for (int value = 0; value < 256; value++) {
int chroma = value - 128;
luma[value] = (value - standard.yOffset) * standard.yScale;
crToR[value] = standard.crToR * chroma;
cbToG[value] = -standard.cbToG * chroma;
crToG[value] = -standard.crToG * chroma;
cbToB[value] = standard.cbToB * chroma;
}
}
private int rgb(int y, int u, int v) {
int base = luma[y];
int r = clamp((base + crToR[v] + 128) >> 8);
int g = clamp((base + cbToG[u] + crToG[v] + 128) >> 8);
int b = clamp((base + cbToB[u] + 128) >> 8);
return (r << 16) | (g << 8) | b;
}
The coefficients live in a ColorStandard enum with four entries — BT.601 and BT.709, each in limited and full range. Switching matrix therefore changes one object, not the conversion loop, and the same renderer handles SD footage and HD footage shot with BT.709.
Step 3: Add NV12, I420, YUY2 and the Rest
Once the chroma addressing is a parameter instead of a constant, the other layouts cost almost nothing. Each format is described by four facts: how chroma is stored (PLANAR, SEMI_PLANAR, PACKED_422, GRAY), how much it is subsampled horizontally and vertically, and whether V comes before U.
NV21("NV21", "4:2:0 semi-planar, VU", Layout.SEMI_PLANAR, 1, 1, true, null, "nv21"),
NV12("NV12", "4:2:0 semi-planar, UV", Layout.SEMI_PLANAR, 1, 1, false, null, "nv12"),
I420("I420", "4:2:0 planar, Y U V", Layout.PLANAR, 1, 1, false, null, "i420", "yu12", "yuv420p"),
YV12("YV12", "4:2:0 planar, Y V U", Layout.PLANAR, 1, 1, true, null, "yv12"),
NV16("NV16", "4:2:2 semi-planar, UV", Layout.SEMI_PLANAR, 1, 0, false, null, "nv16"),
YUY2("YUY2", "4:2:2 packed, Y0 U Y1 V", Layout.PACKED_422, 1, 0, false, PackedOrder.YUYV, "yuy2", "yuyv"),
Y800("Y800", "4:0:0 grayscale", Layout.GRAY, 0, 0, false, null, "y800", "gray", "grey", "y8");
The same record derives the frame size, which is what makes file-size validation possible:
public long frameSize(int width, int height) {
long luma = (long) width * height;
long chromaWidth = (width + (1L << hShift) - 1) >> hShift;
long chromaHeight = (height + (1L << vShift) - 1) >> vShift;
return switch (layout) {
case GRAY -> luma;
case PACKED_422 -> luma * 2;
case SEMI_PLANAR, PLANAR -> luma + 2 * chromaWidth * chromaHeight;
};
}
With that in place, semi-planar decoding is one loop with no branches on the format inside it:
for (int y = 0; y < height; y++) {
int lumaRow = y * width;
int chromaRow = chromaBase + (y >> vShift) * chromaStride;
for (int x = 0; x < width; x++) {
int pair = chromaRow + ((x >> hShift) << 1);
int first = data[pair] & 0xFF;
int second = data[pair + 1] & 0xFF;
int u = vFirst ? second : first;
int v = vFirst ? first : second;
pixels[lumaRow + x] = lut.rgb(data[lumaRow + x] & 0xFF, u, v);
}
}
The planar variant differs only in where U and V start (width * height and width * height + chromaWidth * chromaHeight, swapped for YV12), and the packed variant walks 4-byte macro pixels with a byte-offset table per order. Four loops — planar, semi-planar, packed and grayscale — cover twelve formats.
Step 4: Write Pixels into a BufferedImage
The obvious approach — image.setRGB(x, y, rgb) in the loop — pays a bounds check and a color-model conversion per pixel. TYPE_INT_RGB stores exactly the 0xRRGGBB integers this code produces, so the renderer asks the raster for its backing array and writes into it directly:
public static BufferedImage render(YuvFrame frame) {
BufferedImage image = new BufferedImage(frame.width(), frame.height(), BufferedImage.TYPE_INT_RGB);
int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
byte[] data = frame.data();
Lut lut = new Lut(frame.standard());
switch (frame.format().layout()) {
case PLANAR -> renderPlanar(data, pixels, frame.width(), frame.height(), frame.format(), lut);
case SEMI_PLANAR -> renderSemiPlanar(data, pixels, frame.width(), frame.height(), frame.format(), lut);
case PACKED_422 -> renderPacked422(data, pixels, frame.width(), frame.height(), frame.format(), lut);
case GRAY -> renderGray(data, pixels, lut);
}
return image;
}
YuvFrame is a record that validates on construction: the dimensions must be even where the layout requires it, and the buffer must be at least format.frameSize(width, height) bytes. That single check is what turns “the image is sheared and half gray” into a readable error.
Step 5: Build the Drag-and-Drop Swing Viewer
The window is ordinary Swing: a toolbar with the format, width, height, color matrix and frame index, an image canvas, and a status bar. Files arrive through a DropTarget installed recursively on the content pane, so dropping anywhere in the window works, including on the toolbar:
@Override
public void drop(DropTargetDropEvent event) {
event.acceptDrop(DnDConstants.ACTION_COPY);
File file = firstFile(event.getTransferable());
event.dropComplete(file != null && file.isFile());
if (file != null) {
openFile(file);
}
}
Reading and converting run on a background thread so the window never freezes on a large frame. Every render carries a sequence number, and a result is applied only if it is still the newest one — otherwise fast typing into the width field would let a stale image land on screen after a newer one:
int sequence = renderSequence.incrementAndGet();
renderExecutor.submit(() -> {
byte[] data = FrameReader.readRange(file, offset, length);
BufferedImage image = YuvRenderer.render(new YuvFrame(data, width, height, format, standard));
SwingUtilities.invokeLater(() -> {
if (sequence == renderSequence.get()) {
canvas.setImage(image);
}
});
});
FrameReader uses RandomAccessFile to read only the requested frame, so a 2 GB dump with 1000 frames opens as fast as a single-frame file and the frame spinner stays responsive. The canvas adds the parts that make the tool usable: fit-to-window by default, mouse-wheel zoom anchored at the pointer, drag to pan, and a double click to return to fit.
The repository ships launcher scripts that compile into build/classes on first use, so the whole application is one command:
# Windows
run.cmd 2048x1536.yuv
# macOS / Linux
./run.sh 2048x1536.yuv
Step 6: Detect Width, Height and Layout from the File Name
This is the step that turns a decoder into a tool you can actually use. The parser looks for WxH first, then falls back to the W_H convention, and finally matches a layout token against the aliases declared by each format:
private static final Pattern SIZE_WITH_X =
Pattern.compile("(?<!\\d)(\\d{2,5})\\s*[xX\\u00D7*]\\s*(\\d{2,5})(?!\\d)");
private static final Pattern SIZE_WITH_SEPARATOR =
Pattern.compile("(?<!\\d)(\\d{2,5})[_-](\\d{2,5})(?!\\d)");
Both patterns use negative lookarounds so 2026-11-28 style dates and version numbers do not silently become dimensions, and the result is checked for a plausible aspect ratio before it is accepted. The layout tokens are matched on ASCII word boundaries, which is why nv12 never matches inside nv123.
When the name carries only part of the answer, the byte count finishes the job. Since four formats share the 4:2:0 frame size, the fallback can only narrow the layout down to a family, so it picks the family default (NV21 for 4:2:0, YUY2 for packed 4:2:2) and says so in the status bar. Guesses are never silent, and every field stays editable.
Step 7: Export the Frame as a PNG
Saving is one call, because the rendered BufferedImage is already in the format ImageIO wants:
BufferedImage image = canvas.getImage();
ImageIO.write(image, "png", target);
The viewer writes PNG rather than JPEG on purpose: the frame you are inspecting is usually the only copy of that data, and a lossy round trip would hide exactly the artifacts people open a YUV viewer to find.
Why the Sample No Longer Hand-Writes BMP Files
The first version of this article, published in 2016, wrote BMP files by hand. That was not a stylistic choice: the JDK ships readers for BMP but no writer, so producing one meant assembling the header, the DIB header and the pixel array yourself.
A BMP file starts with a 14-byte header, continues with a 40-byte BITMAPINFOHEADER, and stores every integer in little-endian order while Java writes big-endian by default. Skipping the byte-order fix produces a file that opens and looks wrong rather than failing loudly:

Wrapping the writes in a ByteBuffer with ByteOrder.LITTLE_ENDIAN fixes it:
ByteBuffer buffer = ByteBuffer.allocate(fileSize);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.put(id); // 'B', 'M'
buffer.putInt(fileSize);
buffer.putInt(offset); // 54
buffer.putInt(biSize); // 40
buffer.putInt(biWidth);
buffer.putInt(biHeight);

That custom BMP class has since been removed from the sample. The viewer needs a fast path from bytes to screen, and PNG through ImageIO covers the export case in one line. The BMP header details are still worth knowing if you have to produce a BMP on a platform without an encoder — which is exactly the problem the two screenshots above illustrate.
Common Issues & Edge Cases
- Blue or purple skin tones: the file is NV12 but you decoded it as NV21, or the other way round. Switch the format; the byte count will not change, only the color will.
- The image shears diagonally: the width is wrong. Every row starts one stride late, so the picture slides further sideways as it goes down. Try the other common widths before assuming the data is corrupt.
- The top of the image looks fine and the bottom is gray: the height is larger than the real frame, or the file ends early. Check the file size against
width * height * 3 / 2; the status bar reports a partial trailing frame. - An even-width error for a 4:2:0 or packed 4:2:2 layout: chroma samples are shared by pixel pairs, so odd width or height has no defined meaning. The viewer refuses the combination instead of guessing.
- Colors look washed out or too contrasty: the range and matrix are wrong rather than the layout. Limited-range BT.601 footage decoded as full range loses black and white; HD footage decoded with BT.601 shifts the hues.
- A 2 GB file opens instantly but the image is black: the frame index points past the end of the data. The frame spinner is clamped to
fileSize / frameSize, so check that the format is not inflating the frame size. - Drag and drop does nothing: some IDEs and remote desktop sessions intercept the drop before it reaches the application. Use
File > Open...in that case.