About byte[] and string, Image conversion

byte[] and string conversion

Reference URL: https://www.cnblogs.com/xskblog/p/6179689.html

1. Use System.Text.Encoding.Default, System.Text.Encoding.ASCII, System.Text.Encoding.UTF8, etc. You can also use System.Text.Encoding.UTF8.GetString(bytes).TrimEnd('\0') to add an end marker to a string. (The trial feels ok, the coding method needs to be corresponding)

You can also specify the encoding: System.Text.Encoding.GetEncoding( " gb2312 " ).GetBytes(str);

string  str    = System.Text.Encoding.UTF8.GetString(bytes);   
byte[] decBytes = System.Text.Encoding.UTF8.GetBytes(str); 

2. I don't use it, I don't know how it works

string    str    = BitConverter.ToString(bytes);    
String[] tempArr = str.Split('-');  
byte[]   decBytes = new byte[tempArr.Length];  
for (int i = 0; i < tempArr.Length; i++)  
{  
    decBytes[i] = Convert.ToByte(tempArr[i], 16);  
}

3. In this method, the converted string may contain '+', '/', '=', so if it is used as a url address, it needs to be encoded (how to do not try, because I am not the converted URL, It feels ok to use, I use it to store the database)

string str      = Convert.ToBase64String(bytes);    
byte[] decBytes = Convert.FromBase64String(str); 

  Image to byte[] to base64string conversion (backup)

// In C#      
 // Image to byte[] to base64string conversion: 
Bitmap bmp = new Bitmap(filepath);
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
byte[] arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(arr, 0, (int)ms.Length);
ms.Close();
string  pic = Convert.ToBase64String(arr);
 
// Conversion of base64string to byte[] and then to image: 
byte [] imageBytes = Convert.FromBase64String(pic);
 // Read in MemoryStream object 
MemoryStream memoryStream = new MemoryStream(imageBytes, 0 , imageBytes.Length);
memoryStream.Write(imageBytes, 0, imageBytes.Length);
//转成图片
Image image = Image.FromStream(memoryStream);
 
// In the current database development: the storage methods of pictures are generally CLOB: store base64string BLOB: store byte[]
 // Generally recommend using byte[]. Because the picture can be directly converted to byte[] and stored in the database, if you use base64string, you need to convert from byte[] to base64string. Even more wasteful performance.
View Code

 

4. This method will automatically encode the special characters of the url address, which can be directly used as the url address. But need to rely on System.Web library to use.

string  str    = HttpServerUtility.UrlTokenEncode(bytes);    
byte[] decBytes = HttpServerUtility.UrlTokenDecode(str); 

byte[] and Image conversion

(Reference website: http://www.cnblogs.com/luxiaoxun/p/3378416.html)

1. Convert a picture (png bmp jpeg bmp gif) into a byte array and store it in the database.

2. Convert the byte array read from the database into an Image object and assign it to the corresponding control display.

3. Obtain the format of the corresponding picture from the picture byte array, and generate a picture and save it to the disk.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;

namespace NetUtilityLib
{
    public static class ImageHelper
    {
        /// <summary>
        /// Convert Image to Byte[]
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public static byte[] ImageToBytes(Image image)
        {
            ImageFormat format = image.RawFormat;
            using (MemoryStream ms = new MemoryStream())
            {
                if (format.Equals(ImageFormat.Jpeg))
                {
                    image.Save(ms, ImageFormat.Jpeg);
                }
                else if (format.Equals(ImageFormat.Png))
                {
                    image.Save(ms, ImageFormat.Png);
                }
                else if (format.Equals(ImageFormat.Bmp))
                {
                    image.Save(ms, ImageFormat.Bmp);
                }
                else if (format.Equals(ImageFormat.Gif))
                {
                    image.Save(ms, ImageFormat.Gif);
                }
                else if (format.Equals(ImageFormat.Icon))
                {
                    image.Save(ms, ImageFormat.Icon);
                }
                byte [] buffer = new  byte [ms.Length];
                 // Image.Save() will change the Position of MemoryStream and need to re-Seek to Begin 
                ms.Seek( 0 , SeekOrigin.Begin);
                ms.Read(buffer, 0, buffer.Length);
                return buffer;
            }
        }

        /// <summary>
        /// Convert Byte[] to Image
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static Image BytesToImage(byte[] buffer)
        {
            MemoryStream ms = new MemoryStream(buffer);
            Image image = System.Drawing.Image.FromStream(ms);
            return image;
        }

        /// <summary>
        /// Convert Byte[] to a picture and Store it in file
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static string CreateImageFromBytes(string fileName, byte[] buffer)
        {
            string file = fileName;
            Image image = BytesToImage(buffer);
            ImageFormat format = image.RawFormat;
            if (format.Equals(ImageFormat.Jpeg))
            {
                file += ".jpeg";
            }
            else if (format.Equals(ImageFormat.Png))
            {
                file += ".png";
            }
            else if (format.Equals(ImageFormat.Bmp))
            {
                file += ".bmp";
            }
            else if (format.Equals(ImageFormat.Gif))
            {
                file += ".gif";
            }
            else if (format.Equals(ImageFormat.Icon))
            {
                file += ".icon";
            }
            System.IO.FileInfo info = new System.IO.FileInfo(file);
            System.IO.Directory.CreateDirectory(info.Directory.FullName);
            File.WriteAllBytes(file, buffer);
            return file;
        }
    }
}
View Code

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324975975&siteId=291194637