Преглед на файлове

доделали механиз работы с картинками

fly9024 преди 1 месец
родител
ревизия
9f10a5ba0b

BIN
AvaloniaApplication2/Assets/заглушка.jpg


+ 10 - 0
AvaloniaApplication2/AvaloniaApplication2.csproj

@@ -13,6 +13,10 @@
     <AvaloniaResource Include="Assets\**" />
   </ItemGroup>
 
+  <ItemGroup>
+    <None Remove="Assets\заглушка.jpg" />
+  </ItemGroup>
+
   <ItemGroup>
     <PackageReference Include="Avalonia" Version="11.1.0" />
     <PackageReference Include="Avalonia.Desktop" Version="11.1.0" />
@@ -32,4 +36,10 @@
     </PackageReference>
     <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.18" />
   </ItemGroup>
+
+  <ItemGroup>
+    <AvaloniaResource Update="Assets\заглушка.jpg">
+      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+    </AvaloniaResource>
+  </ItemGroup>
 </Project>

+ 1 - 0
AvaloniaApplication2/Models/TestBase41pContext.cs

@@ -87,6 +87,7 @@ public partial class TestBase41pContext : DbContext
                 .HasColumnType("timestamp without time zone")
                 .HasColumnName("birth_date");
             entity.Property(e => e.IdGender).HasColumnName("id_gender");
+            entity.Property(e => e.Image).HasColumnName("image");
             entity.Property(e => e.Name)
                 .HasColumnType("character varying")
                 .HasColumnName("name");

+ 2 - 0
AvaloniaApplication2/Models/User.cs

@@ -13,6 +13,8 @@ public partial class User
 
     public int IdGender { get; set; }
 
+    public byte[]? Image { get; set; }
+
     public virtual Gender IdGenderNavigation { get; set; } = null!;
 
     public virtual Logined IdUserNavigation { get; set; } = null!;

+ 34 - 2
AvaloniaApplication2/ViewModels/Page2ViewModel.cs

@@ -1,4 +1,5 @@
-using AvaloniaApplication2.Models;
+using Avalonia.Controls.ApplicationLifetimes;
+using AvaloniaApplication2.Models;
 using CommunityToolkit.Mvvm.ComponentModel;
 using Microsoft.EntityFrameworkCore;
 using System;
@@ -6,6 +7,10 @@ using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
+using Avalonia;
+using Avalonia.Platform.Storage;
+using Avalonia.Media.Imaging;
+using System.IO;
 
 namespace AvaloniaApplication2.ViewModels
 {
@@ -13,10 +18,13 @@ namespace AvaloniaApplication2.ViewModels
     {
         [ObservableProperty] User editedUser;
         [ObservableProperty] List<Gender> gendersList;
+        [ObservableProperty] Bitmap imageUser;
+        
         public Page2ViewModel(int id) 
         {
             GendersList = db.Genders.ToList();
-            editedUser = db.Users.Include(x=>x.IdGenderNavigation).FirstOrDefault(x=>x.IdUser == id);            
+            editedUser = db.Users.Include(x=>x.IdGenderNavigation).FirstOrDefault(x=>x.IdUser == id);
+            imageUser = EditedUser.Image != null ? new Bitmap(new MemoryStream(editedUser.Image)) : new Bitmap("Assets/заглушка.jpg");
         }
         public DateTimeOffset DateTimeOffset
         {
@@ -27,5 +35,29 @@ namespace AvaloniaApplication2.ViewModels
         public void GoBack() => MainWindowViewModel.Self.Page = new Page1();
 
         public void Save() => db.SaveChanges();
+        public async Task Image()
+        {
+            if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime desktop ||
+                desktop.MainWindow?.StorageProvider is not { } provider)
+                throw new NullReferenceException("Missing StorageProvider instance.");
+
+            //инициализация в явном виде. менее трушный путь
+            //IClassicDesktopStyleApplicationLifetime desktop = (IClassicDesktopStyleApplicationLifetime)Application.Current?.ApplicationLifetime;
+            // IStorageProvider provider = desktop.MainWindow?.StorageProvider;
+            var files = await provider.OpenFilePickerAsync(new FilePickerOpenOptions()
+            {
+                Title = "Выберите файл с изображением пользователя",
+                AllowMultiple = false               
+            });
+            await using var readStream = await files[0].OpenReadAsync();
+            byte[] buffer = new byte[10000000];
+            var bytes = readStream.ReadAtLeast(buffer, 1);
+            Array.Resize(ref buffer,bytes);
+            editedUser.Image = buffer;
+            ImageUser = new Bitmap(new MemoryStream(editedUser.Image));
+            db.SaveChanges();
+        }
+
+     
     }
 }

+ 2 - 0
AvaloniaApplication2/Views/Page2.axaml

@@ -7,6 +7,7 @@
 			 xmlns:vm="using:AvaloniaApplication2.ViewModels"
 			 x:DataType="vm:MainWindowViewModel">
 	<StackPanel>
+		<Image Source="{Binding Page2VM.ImageUser}" Width="100" Height="100"/>
 		<TextBox Text="{Binding Page2VM.EditedUser.Name}"/>
 		<TextBox Text="{Binding Page2VM.EditedUser.BirthDate}"/>		
 		<DatePicker SelectedDate="{Binding Page2VM.DateTimeOffset}"/>
@@ -17,6 +18,7 @@
 				</DataTemplate>
 			</ComboBox.ItemTemplate>
 		</ComboBox>
+		<Button Content="Выбрать изображение пользователя" Command="{Binding Page2VM.Image}"/>
 		<Button Content="Сохранить изменения" Command="{Binding Page2VM.Save}"/>
 		<Button Content="Развойти обратно" Command="{Binding Page2VM.GoBack}"/>
 	</StackPanel>