Android中Java生成二维码图片尺寸过小,调大崩溃如何解决?
Hey there! It sounds like you're hitting a memory-related crash when trying to bump your QR code's width from 500 to 700. Let's break down why this happens and fix it step by step.
Why the Crash Happens
When you create a Bitmap in Android, it eats up memory based on its dimensions and pixel format. For example, a 700x700 bitmap using the default ARGB_8888 format (4 bytes per pixel) uses ~1.96MB of memory. That might not sound like much, but if your app is already using other memory-heavy resources, or if the device has limited RAM, this can push you over the edge and trigger an OutOfMemoryError.
Fixes to Increase QR Code Size Safely
1. Use a Memory-Efficient Pixel Format
Swap the default ARGB_8888 format for RGB_565 (2 bytes per pixel). This cuts memory usage in half while keeping the QR code scannable. Modify your bitmap creation in the TextToImageEncode method:
// Replace this default line Bitmap bitmap = Bitmap.createBitmap(QRcodeWidth, QRcodeWidth, Bitmap.Config.ARGB_8888); // With this memory-friendly version Bitmap bitmap = Bitmap.createBitmap(QRcodeWidth, QRcodeWidth, Bitmap.Config.RGB_565);
2. Optimize QR Code Generation Logic
Make sure your TextToImageEncode method isn't holding onto unnecessary objects or creating duplicate bitmaps. Here's a streamlined example using ZXing (a common QR code library) that handles larger sizes smoothly:
private Bitmap TextToImageEncode(String value) { BitMatrix bitMatrix; try { bitMatrix = new MultiFormatWriter().encode( value, BarcodeFormat.QR_CODE, QRcodeWidth, QRcodeWidth, new HashMap<>() ); } catch (WriterException e) { e.printStackTrace(); return null; } int width = bitMatrix.getWidth(); int height = bitMatrix.getHeight(); int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { int offset = y * width; for (int x = 0; x < width; x++) { pixels[offset + x] = bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE; } } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; }
3. Clean Up Bitmap Memory Properly
- Always recycle unused bitmaps before assigning a new one to your global
bitmapvariable:
if (bitmap != null && !bitmap.isRecycled()) { bitmap.recycle(); bitmap = null; } bitmap = TextToImageEncode(orderId);
- Once you've uploaded the QR code to Firebase Storage, recycle it immediately to free up memory:
// After successful upload completion if (bitmap != null && !bitmap.isRecycled()) { bitmap.recycle(); bitmap = null; }
4. Debug with Memory Profiler
If crashes persist, use Android Studio's Memory Profiler to track memory usage and spot leaks. You can also test on a low-RAM device to reproduce the issue more reliably.
With these tweaks, increasing your QR code width to 700 should work without crashes. The key is reducing memory overhead and making sure you're cleaning up resources properly.
内容的提问来源于stack exchange,提问作者lasya valiveti

