存储方式 | 实现原理 | 适用场景 |
---|---|---|
SQLite/Room | 将图片转换为字节数组存储至数据库 | 小规模图片(<100KB)、需频繁读写 |
文件系统 | 将图片保存为文件,数据库仅存储路径 | 大量图片、大尺寸图片 |
云存储(扩展) | 图片上传至云端,数据库存储URL | 跨设备同步、节省本地存储 |
// Bitmap转字节数组 ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); byte[] imageBytes = baos.toByteArray();
CREATE TABLE Images ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, image BLOB );
// 插入数据 ContentValues values = new ContentValues(); values.put("name", "example"); values.put("image", imageBytes); db.insert("Images", null, values); // 读取数据 Cursor cursor = db.query("Images", null, "id=?", new String[]{String.valueOf(id)}, null, null, null); if (cursor.moveToFirst()) { byte[] bytes = cursor.getBlob(cursor.getColumnIndex("image")); Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); }
// 获取外部存储路径 File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); File file = new File(dir, "image_" + System.currentTimeMillis() + ".png"); // 压缩并保存 bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(file));
CREATE TABLE Images ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, imagePath TEXT );
// 插入路径 ContentValues values = new ContentValues(); values.put("name", "example"); values.put("imagePath", file.getAbsolutePath()); db.insert("Images", null, values); // 读取并显示图片 Cursor cursor = db.query("Images", null, "id=?", new String[]{String.valueOf(id)}, null, null, null); if (cursor.moveToFirst()) { String path = cursor.getString(cursor.getColumnIndex("imagePath")); Bitmap bitmap = BitmapFactory.decodeFile(path); imageView.setImageBitmap(bitmap); }
内存优化
BitmapFactory.Options
设置 inSampleSize
)。权限管理
WRITE_EXTERNAL_STORAGE
和 READ_EXTERNAL_STORAGE
权限。Scoped Storage
或 MediaStore
API。Base64编码缺陷
Base64编码会增大数据体积(约33%),不建议用于大图片存储。
解答:
解答:
Bitmap.compress()
时降低质量(如JPEG格式,质量设为80)。 BitmapFactory.Options
的 inSampleSize
参数缩小图片尺寸。 Glide
或 Picasso
库自动处理图片缓存和缩放。 ImageView
的固定尺寸,避免内存浪费