Android 如何使用SQLite从库中选择图片并另存为背景图像视图
我是Android编程新手。我想知道如何从gallery中选择图像并将其作为ImageView背景。 我让代码从gallery中进行选择,并将其设置为ImageView背景,但每次我离开应用程序时,图像都会消失。 我必须被保存在数据库里,但我对它知之甚少 如果有人能帮我。。 多谢各位 我的Java文件Android 如何使用SQLite从库中选择图片并另存为背景图像视图,android,sqlite,imageview,Android,Sqlite,Imageview,我是Android编程新手。我想知道如何从gallery中选择图像并将其作为ImageView背景。 我让代码从gallery中进行选择,并将其设置为ImageView背景,但每次我离开应用程序时,图像都会消失。 我必须被保存在数据库里,但我对它知之甚少 如果有人能帮我。。 多谢各位 我的Java文件 ImageView btn1, btn2; Uri photoPath; @Override protected void onCreate(Bundle sa
ImageView btn1, btn2;
Uri photoPath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (ImageView) findViewById(R.id.imageView1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Altere o botão"), 1);
}
});
}
public void onActivityResult(int reqCode, int resCode, Intent data){
if(resCode == RESULT_OK){
if(reqCode == 1){
btn1.setImageURI(data.getData());
}
}
}
我的XML文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context="com.example.camera.MainActivity" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
/>
</LinearLayout>
您必须使用将图像转换为字节,然后使用sqlLite数据库连接来存储和检索图像表单数据库。 为此,请参考此示例:
好的。看起来您用于获取图像并将其设置为Imageview的代码工作正常。 我的建议是将图像保存在本地文件夹中,而不是保存在Sqlite数据库中,因为这样会使数据库变得繁重。但一定要在数据库中保存图像的Uri或路径 使用以下代码将图像保存到本地文件夹中
private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) {
File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/DirName/");
wallpaperDirectory.mkdirs();
}
File file = new File(new File("/sdcard/DirName/"), fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
这是一个关于Sqlite数据库的简单教程