Android端PDF转可缓存Bitmap过大问题的解决方案咨询
地铁线路图PDF转Bitmap内存优化问题
我正在处理一份体积不足1MB的地铁线路图PDF文件,希望在Android应用启动时将其转为Bitmap,以便用户访问MapFragment时可加载缓存的Bitmap进行交互。但目前转换后的Bitmap体积达84MB,超出了内存缓存的承载范围,想咨询可行的优化方案。我已有几个思路:
- 在应用外将PDF转为PNG并作为资源存储,但因地图更新频繁,此方式不够便捷;
- 用户点击MapFragment时再转换PDF为Bitmap,但每次访问会产生约1秒延迟;
- 将转换后的Bitmap存入磁盘缓存,但担心频繁写入磁盘带来负面影响。
以下是我的PDF转换代码:
private Bitmap convertPdfToBitmap() { Bitmap bitmap = null; PdfiumCore pdfiumCore = new PdfiumCore(this); try { File f = FileUtils.fileFromAsset(this, "mappdf.pdf"); ParcelFileDescriptor fd = ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY); PdfDocument pdfDocument = pdfiumCore.newDocument(fd); pdfiumCore.openPage(pdfDocument, 0); // 打开第一页 // 创建Bitmap对象承载页面内容 int width = pdfiumCore.getPageWidthPoint(pdfDocument, 0) * 3; // 发现缩放比例小于3时输出太模糊 int height = pdfiumCore.getPageHeightPoint(pdfDocument, 0) * 3; bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); int bitmapByteCount = bitmap.getByteCount(); Log.i("RootActivity", "Bitmap byte count: " + bitmapByteCount); // 将页面内容渲染到Bitmap对象上 pdfiumCore.renderPageBitmap(pdfDocument, bitmap, 0, 0, 0, width, height); pdfiumCore.closeDocument(pdfDocument); // 记得关闭文档 Log.d("RootActivity", "PDF转换完成"); } catch(Exception e) { Log.e("RootActivity", e.toString()); } return bitmap; }
缓存代码:
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); final int cacheSize = maxMemory / 8; mMemoryCache = new LruCache<String, Bitmap>(cacheSize) { @Override protected int sizeOf(String key, Bitmap bitmap) { return bitmap.getByteCount() / 1024; } }; // 将PDF转为Bitmap并加入缓存 Bitmap bitmap = convertPdfToBitmap(); addBitmapToMemoryCache("mappdf", bitmap);
内容的提问来源于stack exchange,提问作者Shonie
相关产品推荐
相关产品推荐

