You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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。

修复步骤
  1. 替换Bitmap加载逻辑,通过ContentResolver读取Uri对应的输入流加载图片
  2. 增加空值判断,避免无效图片导致崩溃
  3. 可选:添加Bitmap缩放逻辑,避免大图占用内存过高触发OOM
  4. 可选:调整存储路径到系统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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 03:00:01