Android相册多选图片合并为PDF运行报错问题咨询
错误定位
错误出在GalleryImage类的CreatePDF方法中,对应代码行:Bitmap bitmap = BitmapFactory.decodeStream(imageUris.get(i).getPath());
触发崩溃的直接原因是该代码返回的Bitmap为null,后续调用canvas.drawBitmap时传入空对象触发空指针异常。
根本原因:
系统相册返回的图片Uri为content://协议类型,不是本地文件路径,直接调用Uri.getPath()只能拿到类似/document/image:40的路径片段,不是真实的文件存储地址,BitmapFactory无法读取到图片资源,返回null。
修复步骤
- 替换Bitmap加载逻辑,通过ContentResolver读取Uri对应的输入流加载图片
- 增加空值判断,避免无效图片导致崩溃
- 可选:添加Bitmap缩放逻辑,避免大图占用内存过高触发OOM
- 可选:调整存储路径到系统Documents目录,匹配需求
修复后的核心代码
修改CreatePDF方法的图片加载部分:
public void CreatePDF(View view) { File file = getOutputFile(); if (file == null || imageUris.isEmpty()) { return; } try { FileOutputStream fileOutputStream = new FileOutputStream(file); PdfDocument pdfDocument = new PdfDocument(); // 统一配置Bitmap加载参数,避免OOM BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 2; // 可根据PDF页面尺寸动态计算缩放比例 for (int i = 0; i < imageUris.size(); i++) { Uri imageUri = imageUris.get(i); InputStream inputStream = getContentResolver().openInputStream(imageUri); Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options); if (inputStream != null) { inputStream.close(); } // 跳过无效图片 if (bitmap == null) { continue; } PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(350, 500, (i + 1)).create(); PdfDocument.Page page = pdfDocument.startPage(pageInfo); Canvas canvas = page.getCanvas(); Paint paint = new Paint(); paint.setColor(Color.BLUE); canvas.drawPaint(paint); // 可按需缩放Bitmap适配页面大小 canvas.drawBitmap(bitmap, 0f, 0f, null); pdfDocument.finishPage(page); bitmap.recycle(); } pdfDocument.writeTo(fileOutputStream); pdfDocument.close(); fileOutputStream.close(); Toast.makeText(this, "PDF生成成功,保存路径:" + file.getAbsolutePath(), Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); Toast.makeText(this, "PDF生成失败:" + e.getMessage(), Toast.LENGTH_SHORT).show(); } }
可选:修改getOutputFile方法,存储到公共Documents目录
注意:Android 10以下需要申请WRITE_EXTERNAL_STORAGE权限,Android 13+读取相册图片需要申请READ_MEDIA_IMAGES权限。
private File getOutputFile() { File root; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { root = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "My PDF Folder"); } else { root = new File(Environment.getExternalStorageDirectory(), "Documents/My PDF Folder"); } boolean isFolderCreated = true; if (!root.exists()) { isFolderCreated = root.mkdirs(); } if (isFolderCreated) { String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date()); String imageFileName = "PDF_" + timeStamp + ".pdf"; return new File(root, imageFileName); } else { Toast.makeText(this, "存储文件夹创建失败", Toast.LENGTH_SHORT).show(); return null; } }
内容的提问来源于stack exchange,提问作者Anox Software Technology
相关产品推荐
相关产品推荐

