image和字节流之间的相互转换

//将图片转化为长二进制
public Byte[] SetImgToByte(string imgPath)
{
    FileStream file = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
    Byte[] byteData = new Byte[file.Length];
    file.Read(byteData, 0, byteData.Length);
    file.Close();
    return byteData;
}

 

byte[] buf = (byte[])dataTable.Rows[0]["Img"];
MemoryStream ms = new MemoryStream(buf);
Image img = Image.FromStream(ms);

 

img.Save(filePath);

 

public void StreamToFile(Stream stream,string fileName)
{
    // 把 Stream 转换成 byte[]
    byte[] bytes = new byte[stream.Length];
    stream.Read(bytes, 0, bytes.Length);
    // 设置当前流的位置为流的开始
    stream.Seek(0, SeekOrigin.Begin);
    // 把 byte[] 写入文件
    FileStream fs = new FileStream(fileName, FileMode.Create);
    BinaryWriter bw = new BinaryWriter(fs);
    bw.Write(bytes);
    bw.Close();
    fs.Close();
}


public Stream FileToStream(string fileName)
{            
    // 打开文件
    FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
    // 读取文件的 byte[]
    byte[] bytes = new byte[fileStream.Length];
    fileStream.Read(bytes, 0, bytes.Length);
    fileStream.Close();
    // 把 byte[] 转换成 Stream
    Stream stream = new MemoryStream(bytes);
    return stream;
}

 

你可能感兴趣的:(image)