Stream of C # and byte [] related conversion

 forward from

1, converted into binary images

MemoryStream ms = new MemoryStream(bytes);
ms.Position = 0;
Image img = Image.FromStream(ms);
ms.Close();

2, the binary string conversion

Copy the code
System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding();
byte[] inputBytes =converter.GetBytes(inputString);
string inputString = converter.GetString(inputBytes);

string inputString = System.Convert.ToBase64String(inputBytes);
byte[] inputBytes = System.Convert.FromBase64String(inputString);
FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
Copy the code

 

3, Stream each other, and the byte [] Conversion

Copy the code
/// The Stream converted to byte [] 
public byte [] StreamToBytes (Stream Stream) 
{ 
    byte [] bytes = new new byte [Stream.length]; 
    Stream.Read (bytes, 0, bytes.Length); 
    // Set the current as the start position of the stream flow 
    stream.Seek (0, SeekOrigin.Begin); 
    return bytes; 
} 

/// the byte [] turn into stream 
public stream BytesToStream (byte [] bytes) 
{ 
    stream stream new new = the MemoryStream (bytes) ; 
    return Stream; 
}
Copy the code

 

4, between Stream and file conversion

Copy the code
// read the Stream files 
public void StreamToFile (Stream Stream, String fileName) 
{ 
    // Stream converted into byte [] 
    byte [] bytes = new new byte [Stream.length]; 
    Stream.Read (bytes, 0, bytes .length); 
    // set the start position of the current stream is a stream 
    stream.Seek (0, SeekOrigin.Begin); 
    // the byte [] file write 
    the FileStream new new FS = the FileStream (fileName, FileMode.Create); 
    the BinaryWriter BW the BinaryWriter new new = (FS); 
    bw.Write (bytes); 
    bw.close (); 
    fs.Close (); 
} 


// Stream read from a file 
public Stream FileToStream (String fileName) 
{              
    // open the file
    the fileStream = new new fileStream the fileStream (fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
    // read the file byte [] 
    byte [] bytes = new new byte [fileStream.Length]; 
    FileStream.Read (bytes, 0, bytes.Length); 
    fileStream.Close (); 
    // put byte [] is converted into Stream 
    the MemoryStream = new new Stream Stream (bytes); 
    return Stream; 
}
Copy the code

 

5, Bitmap into Byte []

//Bitmap 转化为 Byte[]
Bitmap BitReturn = new Bitmap();
byte[] bReturn = null;
MemoryStream ms = new MemoryStream();
BitReturn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
bReturn = ms.GetBuffer();

Guess you like

Origin www.cnblogs.com/macT/p/11390339.html