Захватывайте, сохраняйте и извлекайте изображения / картинки, используя Sqlite - PullRequest
0 голосов
/ 25 апреля 2020

Как сохранить изображение из imageview в базу данных sqlite и восстановить его снова в Imgeview?

полный код не работает url

1 Ответ

1 голос
/ 26 апреля 2020

Согласно вашему описанию, вы хотите сохранить изображение ImageView в базу данных Sqlite и загрузить изображение из базы данных Sqlite в ImageView, я прав?

Если да, во-первых, вам нужно создать класс для загрузки изображения:

public class Image
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string FileName { get; set; }
    public byte[] Content { get; set; }
}

Затем установка sqlite- net -pcl для соединения с базой данных Sqlite.

Наконец, вам может потребоваться преобразовать изображение вида изображения в байт [] сохранить и преобразовать byte [] в bitmp для загрузки в режиме просмотра изображений.

Пожалуйста, посмотрите полный код:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" 
android:orientation="vertical">

<ImageView android:id="@+id/imageView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" 
    android:src="@drawable/a11"/>

<Button android:id="@+id/button1" 
    android:text="insert image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

<ImageView android:id="@+id/imageView2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

<Button android:id="@+id/button2" 
    android:text="display image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content" 
    android:id="@+id/button3" 
    android:text="create table"/>
</LinearLayout>

 public class MainActivity : AppCompatActivity
{
    private ImageView imageview1;
    private ImageView imageview2;

    private byte[] insertbitmapData;

    private Button btninsert;
    private Button btnload;
    private Button btntable;

    private SQLiteConnection _SQLiteConnection;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.activity_main);


        btninsert = FindViewById<Button>(Resource.Id.button1);
        btninsert.Click += Btninsert_Click;
        btnload = FindViewById<Button>(Resource.Id.button2);
        btnload.Click += Btnload_Click;
        btntable = FindViewById<Button>(Resource.Id.button3);
        btntable.Click += Btntable_Click;
        imageview1 = FindViewById<ImageView>(Resource.Id.imageView1);
        imageview2 = FindViewById<ImageView>(Resource.Id.imageView2);

    }

    private void Btnload_Click(object sender, System.EventArgs e)
    {
        string filename = "test";
        var imagedata = _SQLiteConnection.Table<Image>();
        var d1 = imagedata.Where(x => x.FileName == filename).FirstOrDefault();
        if(d1!=null)
        {
            byte[] imageBytes = d1.Content;             
            using (var ms = new MemoryStream(imageBytes))
            {
                var bitmap = BitmapFactory.DecodeStream(ms);
                imageview2.SetImageBitmap(bitmap);

            }

        }
    }

    private void Btninsert_Click(object sender, System.EventArgs e)
    {
        Bitmap bmp = ((BitmapDrawable)imageview1.Drawable).Bitmap;

        using (var stream = new MemoryStream())
        {
            bmp.Compress(Bitmap.CompressFormat.Png, 0, stream);
            insertbitmapData = stream.ToArray();
        }
        Image image = new Image();
        image.FileName = "test";
        image.Content = insertbitmapData;

        var imagedata = _SQLiteConnection.Table<Image>();

        var d1 = imagedata.Where(x => x.FileName == image.FileName).FirstOrDefault();
        if (d1 == null)
        {
            _SQLiteConnection.Insert(d1);
            Console.WriteLine("Sucessfully Added");
        }
        else
        {
            Console.WriteLine("Already image id Exist");
        }            
    }

    private void Btntable_Click(object sender, System.EventArgs e)
    {
        createsqlite();
    }

    private void createsqlite()
    {
        var fileName = "imagedata.db3";
        var documentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
        var path = System.IO.Path.Combine(documentPath, fileName);

        _SQLiteConnection = new SQLiteConnection(path);
        _SQLiteConnection.CreateTable<Image>();
    }

    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
    {
        Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

public class Image
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string FileName { get; set; }
    public byte[] Content { get; set; }
}

Пример на github:

https://github.com/CherryBu/InsertImage

Обновление:

public class User
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string userName { get; set; }
    public string password { get; set; }
    public string FileName { get; set; }
    public byte[] Content { get; set; }


}
...