繁体   English   中英

无法读取我刚刚保存在Base64中的位图图像

[英]Cannot read a Bitmap image that I just saved in Base64

我尝试加载图片(PNG),将其保存在文本文件中的Base64中并重新加载,但是从文本加载图片后,我只会看到淡淡的图片(黑白,非常丑陋,与原始图片相差甚远!)。文件。 我的问题在哪里?

顺便说一句,所有示例(从图像文件加载图片,保存到base64,从base64加载)均来自SO问题。

首先是从PNG文件加载图片的方式:

try
        {
            var openFileDialog = new OpenFileDialog
                                     {
                                         CheckFileExists = true,
                                         Multiselect = false,
                                         DefaultExt = "png",
                                         InitialDirectory =
                                             Environment.GetFolderPath(Environment.SpecialFolder.MyPictures)
                                     };
            if (openFileDialog.ShowDialog() == true)
            {
                Bitmap img;
                using (var stream = File.Open(openFileDialog.FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    img = new Bitmap(stream);
                }
                Logo.Source = BitmapToImageSource(img);
            }
        }
        catch (Exception exception)
        {
            MessageBox.Show(exception.ToString(), "An error occured", MessageBoxButton.OK, MessageBoxImage.Warning);
        }

将其保存到base64:

try
        {
            Bitmap img = BitmapSourceToBitmap2((BitmapSource) Logo.Source);

            string base64String;

            using (var stream = new MemoryStream())
            {
                img.Save(stream, ImageFormat.Png);
                byte[] imageBytes = stream.ToArray();
                base64String = Convert.ToBase64String(imageBytes);
            }

            string fileName = string.Format(CultureInfo.InvariantCulture, "image{0:yyyyMMddHHmmss}.txt",
                                            DateTime.Now);
            string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), fileName);

            using (var stream = File.Open(path, FileMode.CreateNew, FileAccess.Write, FileShare.None))
            {
                using (var writer = new StreamWriter(stream, System.Text.Encoding.UTF8))
                {
                    writer.Write(base64String);
                    writer.Flush();
                }
            }
        }
        catch (Exception exception)
        {
            MessageBox.Show(exception.ToString(), "An error occured", MessageBoxButton.OK, MessageBoxImage.Warning);
        }

BitmapSourceToBitmap2:

int width = srs.PixelWidth;
        int height = srs.PixelHeight;
        int stride = width*((srs.Format.BitsPerPixel + 7)/8);
        IntPtr ptr = IntPtr.Zero;
        try
        {
            ptr = Marshal.AllocHGlobal(height*stride);
            srs.CopyPixels(new Int32Rect(0, 0, width, height), ptr, height*stride, stride);
            using (var btm = new Bitmap(width, height, stride, PixelFormat.Format1bppIndexed, ptr))
            {
                // Clone the bitmap so that we can dispose it and
                // release the unmanaged memory at ptr
                return new Bitmap(btm);
            }
        }
        finally
        {
            if (ptr != IntPtr.Zero)
                Marshal.FreeHGlobal(ptr);
        }

并将其从文件加载回:

try
        {
            var openFileDialog = new OpenFileDialog
                                     {
                                         CheckFileExists = true,
                                         Multiselect = false,
                                         DefaultExt = "txt",
                                         InitialDirectory =
                                             Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
                                     };
            if (openFileDialog.ShowDialog() == true)
            {
                string base64String;
                using (FileStream stream = File.Open(openFileDialog.FileName, FileMode.Open))
                {
                    using (var reader = new StreamReader(stream))
                    {
                        base64String = reader.ReadToEnd();
                    }
                }

                byte[] binaryData = Convert.FromBase64String(base64String);

                var bi = new BitmapImage();

                bi.BeginInit();
                bi.StreamSource = new MemoryStream(binaryData);
                bi.EndInit();

                Logo.Source = bi;
            }
        }
        catch (Exception exception)
        {
            MessageBox.Show(exception.ToString(), "An error occured", MessageBoxButton.OK, MessageBoxImage.Warning);
        }

这是一个简短的代码序列,它将JPG文件读入字节数组,从中创建一个BitmapSource,然后将其编码为base64字符串并将其写入文件。

第二步,从文件中读取base64字符串,进行解码并创建第二个BitmapSource。

该示例假定存在一些XAML,其中包含两个分别名为image1image2 Image元素。

第1步:

var imageFile = @"C:\Users\Clemens\Pictures\DSC06449.JPG";
var buffer = File.ReadAllBytes(imageFile);

using (var stream = new MemoryStream(buffer))
{
    image1.Source = BitmapFrame.Create(
        stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}

var base64File = @"C:\Users\Clemens\Pictures\DSC06449.b64";
var base64String = System.Convert.ToBase64String(buffer);

File.WriteAllText(base64File, base64String);

第2步:

base64String = File.ReadAllText(base64File);
buffer = System.Convert.FromBase64String(base64String);

using (var stream = new MemoryStream(buffer))
{
    image2.Source = BitmapFrame.Create(
        stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}

如果需要将已经存在的BitmapSource编码为字节数组,请使用如下代码:

var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapSource));

using (var stream = new MemoryStream())
{
    encoder.Save(stream);
    buffer = stream.ToArray();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM