我是android的新手,所以如果这是一个简单的问题,请原谅我,但是我试图在API 21中将图像插入到数据库中,所以我无法使用Files.readAllBytes。我在这里找到了一些将图像转换为数组的代码,但不确定该如何工作,也不确定其返回的内容。然后,我想使用数组并做一个ContentValues.put("Head", (the array) )。提前谢谢大家。
public boolean insertAvatar(Image Head) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//File head = new File("C:capaa\\src\\main\\res\\drawable\\head2.png");
File head = new File("C:capaa\\src\\main\\res\\drawable\\head2.png");
try {
read(head); // calling the convert method on my head file
}catch (IOException e){ }
ContentValues.put("Head",head); // this is the line im not sure about
long ins = db.insert("Avatar", null, contentValues);
return true;
}
//converts to bytes
public byte[] read(File file) throws IOException {
ByteArrayOutputStream ous = null;
InputStream ios = null;
try {
byte[] buffer = new byte[4096];
ous = new ByteArrayOutputStream();
ios = new FileInputStream(file);
int read = 0;
while ((read = ios.read(buffer)) != -1) {
ous.write(buffer, 0, read);
}
}finally {
try {
if (ous != null)
ous.close();
} catch (IOException e) {
}
try {
if (ios != null)
ios.close();
} catch (IOException e) {
}
}
return ous.toByteArray();
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
在Android中将图像存储到数据库通常涉及几个步骤:读取文件为字节数组,然后将这个字节数组插入数据库。你的代码已经很接近正确了,但有几个地方需要调整:
调用read
方法并处理返回值:你需要将read(head)
方法的返回值(即图像的字节数组)赋给一个变量,然后使用这个变量放入ContentValues
。
确保捕获异常:虽然你有异常处理结构,但在实际调用read
方法时没有真正处理异常。应该在外层调用处也妥善处理可能抛出的异常。
使用put
方法的正确参数类型:当你将字节数组放入ContentValues
时,应确保使用正确的键名,并且因为是字节数组,所以使用putBlob
方法而不是简单的put
。
下面是修改后的代码示例:
public boolean insertAvatar(String imagePath) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
try {
// 调用read方法并获取返回的字节数组
byte[] imageData = read(new File(imagePath));
// 使用putBlob方法将字节数组放入ContentValues
contentValues.put("Head", imageData);
long ins = db.insert("Avatar", null, contentValues);
return ins != -1; // 检查插入是否成功
} catch (IOException e) {
// 处理读取文件或数据库操作中的异常
Log.e("DatabaseHelper", "Error inserting image: ", e);
return false;
}
}
// 保持你的read方法不变
public byte[] read(File file) throws IOException {
// ... 你的read方法实现 ...
}
这段代码首先尝试读取指定路径的图像文件为字节数组,然后将这个字节数组通过contentValues.putBlob
方法存入数据库的"Head"列。同时,它改进了异常处理逻辑,确保在遇到问题时能够适当地记录错误信息并返回失败状态。记得替换imagePath
变量为你实际的图像文件路径,并确认数据库表结构中"Head"列被定义为适合存储二进制数据的类型(通常是BLOB)。