C# save image file as string file and convert string as image ,save as image file

 private void ConvertImageToString()
 {
     byte[] bytesArr = File.ReadAllBytes(SelectedBk.ImgUrl);
     string imgBase64Str = Convert.ToBase64String(bytesArr);
     imgFileName = $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}_{Guid.NewGuid().ToString()}_img.txt";
     File.AppendAllText(imgFileName, imgBase64Str);
 }


 private void ConvertFromStringToImage()
 {
     if (File.Exists(imgFileName))
     {
         string baseStr = File.ReadAllText(imgFileName);
         byte[] imgBytes = Convert.FromBase64String(baseStr);
         using (MemoryStream memoryStream = new MemoryStream(imgBytes))
         {
             System.Drawing.Image imgFile = System.Drawing.Image.FromStream(memoryStream);
             SaveFileDialog dialog = new SaveFileDialog();
             dialog.Filter = "Image Files|*.jpg;*.jpeg|All Files|*.*";
             if (dialog.ShowDialog() == true)
             {
                 imgFile.Save(dialog.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
             }
         }
     }
 }
<Window x:Class="WpfApp208.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp208"
        mc:Ignorable="d" WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <ListBox x:Name="lbx" SelectedIndex="0" Grid.Column="0" ItemsSource="{Binding BooksList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                 SelectedItem="{Binding SelectedBk,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Image Source="{Binding ImgUrl}" Width="200" Height="500"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <Image Grid.Column="1" x:Name="img" Source="{Binding SelectedItem.ImgUrl,ElementName=lbx}">
            <Image.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Save as String" Command="{Binding SaveCmd}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContextMenu},Path=PlacementTarget}"/>
                    <MenuItem Header="Save Image File" Command="{Binding SaveImgCmd}"/>
                </ContextMenu>
            </Image.ContextMenu>
        </Image>
    </Grid>
</Window>



//cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Collections;
using System.Drawing;
using Microsoft.Win32;

namespace WpfApp208
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var vm = new BookVM();
            this.DataContext = vm;
        }
    }

    public class BookVM : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(string propName)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propName));
            }
        }

        public BookVM()
        {
            InitData();
        }

        private void InitData()
        {
            var imgsList = Directory.GetFiles(@"..\..\Images");
            int len = imgsList.Length;
            BooksList = new List<Book>();
            for (int i = 0; i < 100000; i++)
            {
                BooksList.Add(new Book()
                {
                    Id = i + 1,
                    ImgUrl = imgsList[i % len]
                });
            }
        }

        private List<Book> booksList;
        public List<Book> BooksList
        {
            get
            {
                return booksList;
            }
            set
            {
                if (booksList != value)
                {
                    booksList = value;
                    OnPropertyChanged(nameof(BooksList));
                }
            }
        }

        private Book selectedBk;
        public Book SelectedBk
        {
            get
            {
                return selectedBk;
            }
            set
            {
                if (value != selectedBk)
                {
                    selectedBk = value;
                    OnPropertyChanged(nameof(SelectedBk));
                }
            }
        }

        private DelCmd saveCmd;
        public DelCmd SaveCmd
        {
            get
            {
                if (saveCmd == null)
                {
                    saveCmd = new DelCmd(SaveCmdExecuted, SaveCmdCanExecute);
                }
                return saveCmd;
            }
        }

        private bool SaveCmdCanExecute(object obj)
        {
            return SelectedBk != null && File.Exists(SelectedBk.ImgUrl);
        }

        string imgFileName { get; set; }
        private void SaveCmdExecuted(object obj)
        {
            ConvertImageToString(); 
        }
        
        private void ConvertImageToString()
        {
            byte[] bytesArr = File.ReadAllBytes(SelectedBk.ImgUrl);
            string imgBase64Str = Convert.ToBase64String(bytesArr);
            imgFileName = $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}_{Guid.NewGuid().ToString()}_img.txt";
            File.AppendAllText(imgFileName, imgBase64Str);
        }

        private DelCmd saveImgCmd;
        public DelCmd SaveImgCmd
        {
            get
            {
                if (saveImgCmd == null)
                {
                    saveImgCmd = new DelCmd(SaveImgCmdExecuted);
                }
                return saveImgCmd;
            }
        }

        private void SaveImgCmdExecuted(object obj)
        {
            ConvertFromStringToImage();
        }

        private void ConvertFromStringToImage()
        {
            if (File.Exists(imgFileName))
            {
                string baseStr = File.ReadAllText(imgFileName);
                byte[] imgBytes = Convert.FromBase64String(baseStr);
                using (MemoryStream memoryStream = new MemoryStream(imgBytes))
                {
                    System.Drawing.Image imgFile = System.Drawing.Image.FromStream(memoryStream);
                    SaveFileDialog dialog = new SaveFileDialog();
                    dialog.Filter = "Image Files|*.jpg;*.jpeg|All Files|*.*";
                    if (dialog.ShowDialog() == true)
                    {
                        imgFile.Save(dialog.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                }
            }
        }
    }

    public class DelCmd : ICommand
    {
        public event EventHandler CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }
            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

        private readonly Action<object> execute;
        private readonly Predicate<object> canExecute;

        public DelCmd(Action<object> executeValue, Predicate<object> canExecuteValue)
        {
            execute = executeValue;
            canExecute = canExecuteValue;
        }

        public DelCmd(Action<object> executeValue) : this(executeValue, null)
        {
        }

        public bool CanExecute(object parameter)
        {
            if (canExecute == null)
            {
                return true;
            }
            return canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            execute(parameter);
        }
    }

    public class Book
    {
        public int Id { get; set; }

        public string ImgUrl { get; set; }
        public string Name { get; set; }
    }
}

 

posted @ 2024-07-12 17:54  FredGrit  阅读(8)  评论(0编辑  收藏  举报