安卓sqlite存储图片完整代码
以下是安卓SQLite存储图片的完整代码示例:
- 在布局文件中添加一个ImageView和一个Button
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"/>
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Choose Image"/>
- 在Java文件中添加以下代码:
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE = 1;
private ImageView imageView;
private Button button;
private Uri imageUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null){
imageUri = data.getData();
imageView.setImageURI(imageUri);
saveImageToDatabase();
}
}
private void saveImageToDatabase(){
try {
InputStream inputStream = getContentResolver().openInputStream(imageUri);
byte[] imageBytes = getBytes(inputStream);
SQLiteDatabase db = this.openOrCreateDatabase("ImagesDB", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS Images (id INTEGER PRIMARY KEY, image BLOB)");
String sql = "INSERT INTO Images (image) VALUES (?)";
SQLiteStatement statement = db.compileStatement(sql);
statement.clearBindings();
statement.bindBlob(1, imageBytes);
statement.executeInsert();
db.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private byte[] getBytes(InputStream inputStream) {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
try {
int len;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
return byteBuffer.toByteArray();
}
}
-
以上代码中,我们使用了SQLite数据库来存储图片。我们首先在图片选择器的回调方法中获取图像的Uri,并将其设置为ImageView的源。然后,我们调用saveImageToDatabase()方法,该方法将图像转换为字节数组,并将其存储在SQLite数据库中。在该方法中,我们首先打开或创建名为“ImagesDB”的数据库。我们创建一个名为“Images”的表,该表具有两个列:ID和Image。Image列是一个BLOB(二进制大对象),它将存储我们的图像。接下来,我们使用SQLiteStatement对象将图像的字节数组插入到数据库中。
-
最后,我们还需要添加以下权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
这些权限将允许我们读取和写入外部存储器。
以上是安卓SQLite存储图片的完整代码示例,希望能帮助到您
原文地址: https://www.cveoy.top/t/topic/eP1x 著作权归作者所有。请勿转载和采集!