【问题标题】:How to convert Base64 image string into image and what file extension to use如何将Base64图像字符串转换为图像以及使用什么文件扩展名
【发布时间】:2014-02-07 08:23:37
【问题描述】:

说,我不知道这个 Base64 图像字符串的图像文件扩展名 从网络服务返回。

如何为 WinRT 处理这些?

  1. 将 Base64 字符串转换为图像后使用哪种类型的图像文件扩展名?

  2. 如何将这个base64图片字符串转换成图片?

使用 WebService 检索数据;

foreach( var ws_item in Results)
{
   InsertItems(ws_item.Picture , ws_item.No, ws_item.Description .... )
}

void InsertItems( string pictureB64String ,..... ) 
{
   //-- for image :

   string _strPicture = PictureB64String;

   //-- convert this base64 string into image and store in a Folder call ImagesFolder 

   ConvertBase64ToImage(_strPicture )
}

void ConvertBase64ToImage(string strPic)
{
}

【问题讨论】:

  • 嗯,您可以尝试的一件事是将图像加载到BitmapDecoder(应该能够处理几乎任何类型),然后将其编码为您想要的任何类型的文件。
  • 这是来自网络服务的 Base64 字符串。如果您能告诉我如何完成这项任务,将不胜感激。
  • 我不会为你做,但我会描述步骤。首先,查看the BitmapDecoder class。注意静态CreateAsync 方法。如果您阅读不接受Guid 的方法,您会注意到它会自动选择正确的解码器。然后你需要做的是将base64 string 转换成IRandomAccessStream。我可能会使用内置的 Windows 运行时互操作扩展和CryptographicBuffer.CreateFromBase64String 来做到这一点。

标签: c# base64 winrt-xaml


【解决方案1】:

我想最好的转换方法是先转换成字节数组,然后从字节数组中获取 de mime 类型

样本:

     byte[] image = Convert.FromBase64String(content);
     string extensao = GetMimeFromBytes(image);


public static int MimeSampleSize = 256;

        public static string DefaultMimeType = "application/octet-stream";

        [DllImport(@"urlmon.dll", CharSet = CharSet.Auto)]
        private extern static uint FindMimeFromData(
            uint pBC,
            [MarshalAs(UnmanagedType.LPStr)] string pwzUrl,
            [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,
            uint cbSize,
            [MarshalAs(UnmanagedType.LPStr)] string pwzMimeProposed,
            uint dwMimeFlags,
            out uint ppwzMimeOut,
            uint dwReserverd
        );

        public static string GetMimeFromBytes(byte[] data)
        {
            try
            {
                uint mimeType;
                FindMimeFromData(0, null, data, (uint)MimeSampleSize, null, 0, out mimeType, 0);

                var mimePointer = new IntPtr(mimeType);
                var mime = Marshal.PtrToStringUni(mimePointer);
                Marshal.FreeCoTaskMem(mimePointer);

                return mime ?? DefaultMimeType;
            }
            catch
            {
                return DefaultMimeType;
            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 2018-09-07
    • 2014-07-21
    • 2014-09-14
    • 2021-12-15
    相关资源
    最近更新 更多