Android 返回null的位图工厂
我正在尝试制作一个应用程序,在其中我需要在SQLite数据库中存储和检索图像。我让程序使用BLOB将图像存储为字节数组,我也能够检索字节数组,但在将数组解码为位图时,BitmapFactory返回null。请帮忙。 这是我用来解码数组的代码Android 返回null的位图工厂,android,sqlite,bitmapfactory,Android,Sqlite,Bitmapfactory,我正在尝试制作一个应用程序,在其中我需要在SQLite数据库中存储和检索图像。我让程序使用BLOB将图像存储为字节数组,我也能够检索字节数组,但在将数组解码为位图时,BitmapFactory返回null。请帮忙。 这是我用来解码数组的代码 Cursor c=db.rawQuery("SELECT * FROM student WHERE name='"+"1"+"'", null); if(c.moveToFirst()) {
Cursor c=db.rawQuery("SELECT * FROM student WHERE name='"+"1"+"'", null);
if(c.moveToFirst())
{
byte[] outImage=c.getBlob(1);
Log.d("The out image is", String.valueOf(outImage));
Bitmap bitmap = BitmapFactory.decodeByteArray(outImage , 0, outImage .length);
iv.setImageBitmap(bitmap);
}
这是我在数据库中插入字节[]的方式:
if(requestCode==CAMERA_REQUEST && resultCode==RESULT_OK){
Bitmap yourImage = (Bitmap) data.getExtras().get("data");
// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
Log.e("output before conversion", imageInByte.toString());
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.execSQL("INSERT INTO student VALUES('"+"1"+"','"+imageInByte+"');");
Log.d("Success: ", "Image Saved");
}
logcat读的是这样的内容
12-24 23:39:49.777: E/output before conversion(22523): [B@13fd7069
12-24 23:39:49.778: D/Insert:(22523): Inserting ..
12-24 23:39:49.840: D/Success:(22523): Image Saved
12-24 23:39:51.579: D/The out image is(22523): [B@155f0aee
12-24 23:39:51.580: D/skia(22523): --- SkImageDecoder::Factory returned null
解码器返回
null
,因为您没有传递有效数据。
首先将blob
转换为byteArray
Blob blob = c.getBlob(1);
int blobLength = (int) blob.length();
byte[] outImage = blob.getBytes(1, blobLength);
Log.d("The out image is", String.valueOf(outImage));
Bitmap bitmap = BitmapFactory.decodeByteArray(outImage , 0, outImage .length);
iv.setImageBitmap(bitmap);
blob.free();
我不认为你可以像这样从blob中获取字节数组:“我正在让程序使用blob将图像存储为字节数组”-不要。让文件系统来管理这样的事情。将图像存储为常规文件,并在数据库中只保留文件名(和路径)。@JASONGPETERSON感谢链接,它很有帮助@米肯。我也想到了这一点,但就我而言,这是最好的方法,所以我坚持使用SQLite。无论如何,谢谢。我尝试了你的代码,它要求我在第一行将blob的类型更改为byte[]@斯瓦普尼尔哈坎特:是的。你是对的。。实际上你不必皈依。请让我知道您是如何将blob插入数据库的。我正在使用一个简单的查询将blob插入数据库。实际上,我将相机拍摄的照片转换为字节[],然后使用查询将其插入数据库。我怀疑您的字节数组。做一件事。比较您的this字节数组
byte[]outImage=c.getBlob(1)代码>带有从摄影机返回的字节数组。只是想澄清一下,你得到的是真实的数据。您可以使用数组比较两字节数组。相等(第一,第二)
嘿,Praveen,正如您所说,我试过了,但是数组不匹配。你知道为什么会这样吗?我已经更新了问题并插入了代码,我正在使用该代码在数据库中插入字节[]。请看一看。谢谢