A 12 MP phone capture decodes into about 48 MB of memory and uploads as a 3-5 MB JPEG over a mobile link. If the server only needs a preview, that is roughly 20 times more bytes and RAM than the job requires. This how-to sizes the decode before it happens: read the image dimensions without allocating pixels, compute BitmapFactory.Options.inSampleSize as the largest power of two that keeps both dimensions at or above your target, then compress once to JPEG at a quality that fits the byte budget. The same steps work for a photo from the phone camera or a frame from a USB board camera the app drives. Keep saving the full image to the gallery; only the server copy gets smaller.
What inSampleSize does to a decode
BitmapFactory.Options.inSampleSize tells the decoder to keep one pixel in every N of each direction. A value of 2 halves the width and the height, 4 quarters them, and so on. The decoder accepts any positive value but rounds it down to the nearest power of two, so 3 decodes exactly like 2. A value of 0 or below leaves the bitmap at full size.
To choose the value before any pixels are allocated, run a bounds decode first. Set inJustDecodeBounds to true, call BitmapFactory.decodeByteArray() or decodeFile(), and read outWidth and outHeight from the same Options object. That pass costs no bitmap memory, and sizing the allocation before you make it is the same discipline as checking a multi-channel image buffer size before processing.
The rule for the value itself:
Both comparisons are >=, so the decoded image lands at or slightly above the request, never below it.
Worked example: a 4000 × 3000 photo down to a 1000 × 750 upload
The inputs, and where each comes from:
- Capture 4000 × 3000 px — the standard output of a 12 MP phone camera, the case in the question.
- Target 1000 × 750 px, so
reqWidth= 1000 andreqHeight= 750 — chosen from the consumer: the server stores a preview that displays at most 1000 px wide. - 4 bytes per decoded pixel — the ARGB_8888 default configuration.
The rule in words: halve both dimensions repeatedly; the last power of two that still leaves each dimension at or above its request is the answer. The arithmetic:
- 2: 4000 / 2 = 2000 >= 1000 and 3000 / 2 = 1500 >= 750 — passes, but 2000 × 1500 still holds 4× the pixels the preview needs.
- 4: 4000 / 4 = 1000 >= 1000 and 3000 / 4 = 750 >= 750 — passes exactly.
- 8: 4000 / 8 = 500 < 1000 — fails, so the loop stops at 4.
Result: inSampleSize = 4. The decode drops from 12,000,000 px × 4 B = 48 MB to 750,000 px × 4 B = 3 MB of RAM. Compressed at quality 85, the full frame runs 3-5 MB as a JPEG and the 1000 × 750 copy runs 150-300 KB; detailed scenes land at the high end of both ranges. On a typical photo the upload falls by about 20×.
| inSampleSize | Decoded size | Decode RAM, ARGB_8888 | Typical JPEG, quality 85 |
|---|---|---|---|
| 1 | 4000 × 3000 | 48 MB | 3-5 MB |
| 2 | 2000 × 1500 | 12 MB | 800 KB-1.4 MB |
| 4 | 1000 × 750 | 3 MB | 150-300 KB |
| 8 | 500 × 375 | 750 KB | 40-80 KB |
Decision: decode at 4 and compress once at quality 85. If the upload is still over its byte budget, step quality down 85, 80, 75; shrink the pixels again only when quality alone cannot reach the target.
The steps, in order
- Decode the bounds. No pixels are allocated in this pass, whatever the image size.
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(jpegBytes, 0, jpegBytes.length, bounds);
// bounds.outWidth and bounds.outHeight are now filled in
-
Compute the sample size. The helper doubles
inSampleSizeuntil the next doubling would break one of the two requests.
static int sampleSizeFor(BitmapFactory.Options bounds, int reqWidth, int reqHeight) {
int inSampleSize = 1;
if (bounds.outHeight > reqHeight || bounds.outWidth > reqWidth) {
while (bounds.outHeight / (inSampleSize * 2) >= reqHeight
&& bounds.outWidth / (inSampleSize * 2) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
- Test the helper on the worked case. With bounds from a 4000 × 3000 capture and a 1000 × 750 request, it must return 4.
BitmapFactory.Options test = new BitmapFactory.Options();
test.outWidth = 4000;
test.outHeight = 3000;
assertEquals(4, sampleSizeFor(test, 1000, 750)); // 4000 / 4 = 1000, 3000 / 4 = 750
-
Decode small and compress once. On a low-memory device, set
opts.inPreferredConfig = Bitmap.Config.RGB_565before the decode to halve decode RAM again; JPEG carries no alpha, so the upload stays correct.
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = sampleSizeFor(bounds, 1000, 750);
Bitmap small = BitmapFactory.decodeByteArray(jpegBytes, 0, jpegBytes.length, opts);
ByteArrayOutputStream out = new ByteArrayOutputStream();
small.compress(Bitmap.CompressFormat.JPEG, 85, out);
byte[] uploadBytes = out.toByteArray();
small.recycle();
-
Upload, then clean up. Post
uploadBytesto the server, and delete the cache file in afinallyblock if you wrote one, so failed uploads leave nothing behind.
Verify it worked
Log the decoded size and the byte count just before the upload:
Log.d(TAG, small.getWidth() + "x" + small.getHeight() + " " + uploadBytes.length + " B");
Both dimensions should sit at or slightly above the request: a 4032 × 3024 capture at sample 4 decodes to 1008 × 756, and whole-pixel rounding up like that is normal. small.getAllocationByteCount() should report about 3 MB for the worked case.
Common mistakes
- Hard-coding the sample size. A value tuned for one sensor decodes the wrong size on the next device; always compute it from the bounds pass.
- Passing a non-power of two. A request of 3 quietly decodes at 2, half the reduction you expected.
- Raising JPEG quality to fix blur. Sampling blur is already in the pixels; quality only trades JPEG artifacts against bytes.
- Compressing photos as PNG. On photographic content PNG lands several times larger than JPEG at quality 85; keep PNG for UI graphics and line art.
- Decoding full size to look at the image first. The bounds pass exists so the full bitmap is never allocated; a 48 MB decode on a low-memory device is how OutOfMemoryError happens.
When downsampling is the wrong fix
Sampling throws pixels away before compression, and no quality setting brings them back. If the server measures the part, crops tightly, or reads codes or text, size the decode to the smallest feature it must see: a Code 128 module needs about 2 pixels across after the decode, which the Code 128 barcode module size, reading angle and reader distance guide works through, and OCR accuracy falls off below roughly a 20-pixel cap height.
If the capture source is a vision or board camera rather than the phone sensor, fix the size at the device. Getting more than a QVGA stream out of a small board camera is its own setup, covered by capturing images above QVGA resolution on small camera boards, and matching the delivered resolution to the downscale beats resizing blind, as downscale images after capture and match on-camera resolution explains. To pick such a camera, the area scan cameras category sorts by resolution, the camera finder narrows by sensor and interface, and the camera configurator steps through the whole chain.
Ship checklist
- Bounds pass before every decode. You never allocate an image of unknown size.
-
inSampleSizecomputed, never hard-coded. Sensor sizes change between devices; a constant breaks on the next model. - Both decoded dimensions logged and at or above the request. Whole-pixel rounding puts decoded size slightly above, never below.
-
EXIF orientation applied before
compress(). Applied after, the file is already written sideways. - Quality 85 first, stepped by 5 to hit the byte budget. Pixel dimensions stay fixed; only the artifacts change.
- Smallest feature still 2 px or more after sampling when the server reads codes or text.
- Cache file deleted once the upload returns. Failed uploads otherwise pile up in storage.
If the capture device is a vision camera and the sizes still do not add up, describe the sensor, the stream size and the server limit through the contact page and we will work the numbers with you.
Questions
Does inSampleSize have to be a power of two?
Any positive value is accepted, but the decoder rounds it down to the nearest power of two before sampling, so 3 behaves like 2 and 6 like 4. In practice you pass 1, 2, 4, 8 or 16. A value of 0 or negative leaves the full-size decode in place, so make the helper return at least 1 on every path.
Does decodeByteArray honor inSampleSize the same way as decodeFile?
Yes. The sample size is a property of BitmapFactory.Options, not of the source, so decodeByteArray, decodeFile and decodeResource all honor it identically. Use the same bounds pass before each call: set inJustDecodeBounds to true, decode, read outWidth and outHeight, then set it back to false for the real decode. Do not parse dimensions from the JPEG header yourself; the bounds pass already reports them.
How much JPEG quality should the upload use?
Start at 85 and tune from there. Between 85 and 100 the file grows quickly for little visible improvement on a phone-sized preview; below about 70, blocking artifacts show up around text and straight edges. If the upload is still over its byte budget, step quality down in increments of 5 — 85, 80, 75 — before you shrink the pixel dimensions again.
How far can sampling go before server-side code reading fails?
Keep the smallest feature at 2 pixels or more after the decode: a Code 128 module needs about 2 pixels across, and OCR accuracy falls off below roughly a 20-pixel cap height. From a 4000 × 3000 capture, a 300-module barcode spans 3000 sensor pixels; at inSampleSize 4 it decodes to 750 px, 2.5 px per module — readable. At 8 it is 375 px, 1.25 px per module, below the floor. Sample to the smallest feature the server must read, not to the display.
When does RGB_565 make sense for an upload?
RGB_565 stores 2 bytes per pixel instead of the 4 that ARGB_8888 uses, halving decode memory again — 1.5 MB instead of 3 MB for the 1000 × 750 case. JPEG has no alpha channel, so nothing is lost there, but 5- and 6-bit channels can band on smooth gradients. Use it when heap is tight; stay on ARGB_8888 when the server re-crops or measures.
Where should the compressed bytes wait before the upload starts?
Up to a few hundred kilobytes, a ByteArrayOutputStream in memory is fine — the 1000 × 750 JPEG from the worked example lands there. Above roughly 1 MB, write the file to the app cache directory and stream from disk so the byte array and the bitmap never sit in the heap together. Delete the cache file in a finally block once the upload returns, success or not.