图片二进制转换与存入数据库相关

关于转换问题,刚开始我需要从数据库读出一个二进制数据流,并将其转换成一个Image格式。

在不涉及数据库的情况下,我先将一个图片转换成一个二进制数组显示出来,再写一个方法将其转换成图片image格式。

一、 先不涉及数据库,将图片转换成二进制,在将二进制转换成图片。

1.protected void Button1_Click(object sender, EventArgs e)
  {
  string str = null;
  PictureToBinary ptb = new PictureToBinary();
  // str = Convert.ToBase64String( ptb.Data("E:/workspace/asp/TEST/PictureTurnToBinary/PictureTurnToBinary/img/Tulips.jpg"));

  Image newImage = Image.FromFile(Server.MapPath("Tulips.jpg"));
  str =Convert.ToBase64String( ptb.PhotoImageInsert(newImage));
  Label1.Text = str;
//label可以用response代替(response.write(str);)

 


  }

 

 

第一步,我将图片转换成二进制数组,并转换成string格式,用一个Label展现(也可以用Response直接输出到页面显示)。产生的数组并不是二进制构成的数据流而是一串字节,如下:

所以建议先将图片压缩一下,不然会很大。

第二步,将得到的二进制字节码转换为图片格式。

2. protected void Button2_Click(object sender, EventArgs e)
   {
     PictureToBinary ptb = new PictureToBinary();
     Image newImage = Image.FromFile(Server.MapPath("Tulips.jpg"));
     WritePhoto(ptb.PhotoImageInsert(newImage));
   }
//图片输出到页面
 public void WritePhoto(byte[] streamByte)
   {
     Response.ContentType = "image/JPEG";
     Response.BinaryWrite(streamByte);
  }
 public class PictureToBinary
  {

    public PictureToBinary()
    {
      //
      // TODO: 在此处添加构造函数逻辑
      //

   }

public byte[] PhotoImageInsert(System.Drawing.Image imgPhoto)
  {
  //将Image转换成二进制流数据

  MemoryStream mstream = new MemoryStream();
  imgPhoto.Save(mstream, System.Drawing.Imaging.ImageFormat.Bmp);
  byte[] myData = new Byte[mstream.Length];
    mstream.Position = 0;
  mstream.Read(myData, 0, myData.Length);
    mstream.Close();
  return myData;
  }
}

 


 

结果如下:

 

 二、将得到的二进制数据保存到数据库,再将其读出。

 需要用到这么几个控件:一个fileLoad控件,两个按钮,分别是存入和读取。

存入图片到数据库:

protected void Saveintodatabase_Click(object sender, EventArgs e)
{
  //将图片保存到数据库
  //加载文件,并以字节数组格式存入数据库
  HttpPostedFile loadPhoto = FileUpload1.PostedFile;
  //获取记载图片内容长度
  int photoLength = loadPhoto.ContentLength;
  //存为字节数组
  byte[] photoArray = new byte[photoLength];
  Stream photoStream = loadPhoto.InputStream;
  photoStream.Read(photoArray, 0, photoLength);
  //连接数据库读取文件
  SqlConnection conn = new SqlConnection();
  conn.ConnectionString = "Data Source=localhost;Database=Test;User Id=sa;Pwd=123456789";
  string sql = "insert into Test_Picture values(@image,3)";
  SqlCommand cmd = new SqlCommand(sql,conn);
  cmd.CommandType = System.Data.CommandType.Text;
  cmd.Parameters.Add("@image",SqlDbType.Image);
  cmd.Parameters["@image"].Value = photoArray;
  conn.Open();
  //执行sql,成功执行返回1,否则返回0(insert,update,delete),其他命令返回-1
  int row = cmd.ExecuteNonQuery();
  Response.Write(row);
  conn.Close();
}

 

读取文件:

protected void PhotoShowInWebSite_Click(object sender, EventArgs e)
{
  //读取数据库图片文件,并保存到本地。
  SqlConnection conn = new SqlConnection();
  conn.ConnectionString = "Data Source=localhost;Database=Test;User Id=sa;Pwd=123456789";

  //选择你需要的字段值,这边就直接赋值了
  string sql = "select Picture from Test_Picture where Number = 3";
  SqlCommand cmd = new SqlCommand(sql, conn);
  byte[] MyData = new byte[0]; 
  try
  {
    conn.Open();
    SqlDataReader mySqlDataReader;
    mySqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
    if (mySqlDataReader.Read())
    {
      Response.Clear();

      Response.ContentType = "image/JPEG";
      Response.BinaryWrite((byte[])mySqlDataReader["Picture"]);

      /*将图片写入到本地d盘      

      //图片字节流

      MyData = (byte[])mySqlDataReader["Picture"];

      int ArraySize = MyData.GetUpperBound(0);
      FileStream fs = new FileStream(@"d:\02.jpg", FileMode.OpenOrCreate, FileAccess.Write);
      fs.Write(MyData, 0, ArraySize);
      fs.Close();

      */

    }
    
  } catch (SqlException SQLexc)
  {
    Response.Write(SQLexc.ToString());
  }

    conn.Close();
}

 

 

以上为整理的为图片二进制转换与存取数据库相关的内容。

 

新人报道,请多指教!

 

posted @ 2019-01-22 16:19  The_Invisible  阅读(1220)  评论(2编辑  收藏  举报