【发布时间】:2025-11-29 07:05:03
【问题描述】:
我是 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();
}
【问题讨论】:
-
在
"C:capaa\\src\\main\\res\\drawable\\head2.png"中C:之后缺少反斜杠是故意的吗?如果这应该适用于 Android,为什么要使用明显的 Windows 路径? -
@stickybit 我试图在我的可绘制文件夹中获取一张图片,然后剪切路径,因为它对于这篇文章来说是巨大的。您知道获取可绘制文件的最佳方法,还是列出整个路径的唯一方法?我可以简单地做“drawable/head2.png”
-
@stickybit 我也试过 "String HeadUri = "drawable://" + R.drawable.head2;"但在读取方法 cri 中仍然无法识别