C#⽂件转byte数组,byte数组再转换⽂件using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//----引⼊必要的命名空间
using System.IO;
using System.Drawing.Imaging;
namespace FileStreamOperator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private byte[] photo;//公⽤缓冲区
public string SourFilePath;//源图⽚⽂件路径
public string ObjFilePath;//⽬标图⽚路径
private void btnOuput_Click(object sender, EventArgs e)
字符串数组怎么转成byte
{
try
{
SourFilePath = txtInputPath.Text.Trim();
string outputPath = txtOutputPath.Text.Trim();
string outputFileName = txtOutputFileName.Text.Trim();
ObjFilePath = outputPath +"\\"+ outputFileName;
if (SourFilePath == "" || outputPath == "" || outputFileName == "")
{
MessageBox.Show("输⼊路径和输出路径不能为空!");
return;
}
FileToStream();
StreamToFile();
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
private void btnSelectInput_Click(object sender, EventArgs e)
{
txtInputPath.Text=selectFile();
}
private string selectFile() {
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
return openFileDialog1.FileName;
}
else {
return "";
}
}
private string selectFolder()
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
return folderBrowserDialog1.SelectedPath;
}
else
{
return "";
}
}
private void btnSelectOutput_Click(object sender, EventArgs e)
{
txtOutputPath.Text = selectFolder();
}
private void btnClear_Click(object sender, EventArgs e)
{
txtInputPath.Text = "";
txtOutputFileName.Text = "";
txtOutputPath.Text = "";
}
public int StreamToFile()//反向转换
{
byte[] bytes = photo;
FileStream fs = new FileStream(ObjFilePath, FileMode.Create, FileAccess.Write); fs.Write(bytes, 0, bytes.Length);
fs.Flush();
fs.Close();
return 0;
}
public int imgToStream()//图⽚到流的转换
{
Image img = new Bitmap(SourFilePath);
MemoryStream stream = new MemoryStream();
img.Save(stream, ImageFormat.Bmp);
BinaryReader br = new BinaryReader(stream);
photo = stream.ToArray();
stream.Close();
return 0;
}
public int FileToStream()//⽂件到流的转换
{
photo = File.ReadAllBytes(SourFilePath);
return 0;
}
public Image ShowPic()//根据流显图
{
byte[] bytes = photo;
MemoryStream ms = new MemoryStream(bytes);
ms.Position = 0;
Image img = Image.FromStream(ms);
ms.Close();
return img;
}
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。