简体   繁体   中英

How to convert Base64 image string into image and what file extension to use

Say, I dont know the image file extension from this Base64 image string return from webservice.

How to handle these for WinRT?

  1. What type of image file extension to use AFTER converting Base64 string to image?

  2. How to convert this base64 image string into image?

Retrieving Data with 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)
{
}

I guess that the best way to convert is first convert into byte array, after get de mime type from byte array

sample:

     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;
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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