当前位置:首页 > 行业动态 > 正文

安卓图片转化二进制放入数据库

将Bitmap转为字节数组,通过Base64编码或直接存入SQLite数据库BLOB字段,注意压缩图片

图片获取与转换

在安卓中,图片通常来自两种途径:本地文件网络资源,以下以本地文件为例,演示如何将图片转换为二进制数据。

获取图片文件

// 通过文件路径获取图片
File imageFile = new File("/storage/emulated/0/Pictures/example.jpg");

转换为二进制(字节数组)

// 将图片压缩为字节数组(PNG格式)
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] imageBytes = baos.toByteArray();

数据库准备

使用 SQLite 数据库存储二进制数据,需创建包含 BLOB 类型的表。

创建表语句

CREATE TABLE Images (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT,
    data BLOB
);

数据库操作工具类

public class DBHelper extends SQLiteOpenHelper {
    public DBHelper(Context context) {
        super(context, "image_db", null, 1);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE Images (id INTEGER PRIMARY KEY, name TEXT, data BLOB)");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS Images");
        onCreate(db);
    }
}

插入二进制数据到数据库

插入数据

// 初始化数据库
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
// 插入数据
ContentValues values = new ContentValues();
values.put("name", "example_image");
values.put("data", imageBytes); // 直接存储字节数组
long rowId = db.insert("Images", null, values);

查询并还原图片

// 查询数据
Cursor cursor = db.query("Images", null, "id=?", new String[]{String.valueOf(rowId)}, null, null, null);
if (cursor.moveToFirst()) {
    byte[] retrievedBytes = cursor.getBlob(cursor.getColumnIndex("data"));
    Bitmap bitmap = BitmapFactory.decodeByteArray(retrievedBytes, 0, retrievedBytes.length);
    imageView.setImageBitmap(bitmap); // 显示图片
}
cursor.close();

注意事项

问题 解决方案
大图片导致内存溢出 使用 BitmapFactory.Options 进行图片压缩或采样
数据库文件过大 考虑将图片存储到文件系统,数据库仅保存路径
多线程操作冲突 使用 AsyncTaskThread 处理数据库IO操作

完整示例代码

// 1. 获取图片并转换为二进制
File imageFile = new File("/path/to/image.jpg");
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] imageBytes = baos.toByteArray();
// 2. 插入数据库
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "test_image");
values.put("data", imageBytes);
db.insert("Images", null, values);
// 3. 查询并显示图片
Cursor cursor = db.query("Images", null, "name=?", new String[]{"test_image"}, null, null, null);
if (cursor.moveToFirst()) {
    byte[] bytes = cursor.getBlob(cursor.getColumnIndex("data"));
    Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    imageView.setImageBitmap(bmp);
}
cursor.close();

相关问题与解答

问题1:如何优化大图片的存储性能?

解答

  1. 压缩图片:在转换为二进制前,使用 Bitmap.compress() 降低质量(如从100%降到80%)。
  2. 分块存储:将大文件分割为多个小块,分批次写入数据库。
  3. 异步处理:使用 AsyncTaskExecutorService 在子线程中执行IO操作,避免阻塞主线程。

问题2:数据库中的二进制图片如何加密?

解答

  1. AES加密:在存储前对字节数组进行AES加密,取出时解密。
    // 加密示例(需引入BouncyCastle库)
    SecretKeySpec key = new SecretKeySpec("1234567890abcdef".getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] encrypted = cipher.doFinal(imageBytes);
  2. 自定义加密算法:根据需求设计简单加密逻辑(如异或操作),但安全性
0