获取网络图片并显示在picturbox上,byte[]数组转换成Image:

时间:2022-04-15 04:37:11
   private void getWebPicture_Click(object sender, EventArgs e)
{
WebRequest request = WebRequest.Create("http://d.hiphotos.baidu.com/image/h%3D200/sign=6008b360f336afc3110c38658318eb85/a1ec08fa513d26973aa9f6fd51fbb2fb4316d81c.jpg");
WebResponse response = request.GetResponse();
Stream s=response.GetResponseStream();
byte[] data = new byte[];
int length = ;
MemoryStream ms = new MemoryStream();
while ((length=s.Read(data,,data.Length))>)
{
ms.Write(data, , length);
}
ms.Seek(, SeekOrigin.Begin);
pictureBox1.Image = Image.FromStream(ms);
}

byte[]数组转换成Image:

   private byte[] ImageTobyteshuzu(Image image)
{
MemoryStream ms = new MemoryStream();
Bitmap bi = new Bitmap(image);
bi.Save(ms, image.RawFormat);
byte[] data = new byte[ms.Length];
ms.Seek(, SeekOrigin.Begin);
ms.Read(data, , data.Length);
return data;
}

Image转换成byte[]数组:

     private Image byteshuzuToImage(byte[] imageBytes)
{
MemoryStream ms = new MemoryStream();
ms.Write(imageBytes, , imageBytes.Length);
ms.Seek(, SeekOrigin.Begin);
Image i = Image.FromStream(ms);
return i;
}

最后说一下,使用了memeoryStream的write和read方法以后,最好一定要把流指针回到最开始的地方!!! 我因为这个问题老是转换失败,困扰了很久!!!  写这篇博客,以便巩固。

wpf:将iv1上获取到的网络图片存到数据库,并从数据库中读取并显示到Image上:

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            if (iv1.Source!=null)
            {
                BitmapImage bi = (BitmapImage)iv1.Source;
                Stream s=bi.StreamSource;
                s.Seek(, SeekOrigin.Begin);
                byte[] data = new byte[s.Length];
                s.Read(data, , data.Length);
                saveImageToSqlServer(data);
                getImageFromSqlServer();
            }
            else
            {
                MessageBox.Show("请先获取图片!");
            }
        }

保存到数据库:

        private void saveImageToSqlServer(byte[] data)
{
SqlConnection conn = new SqlConnection(connectString);
conn.Open();
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandText = "delete from tb1";
comm.ExecuteNonQuery();
comm.Connection = conn;
comm.CommandText = "insert into tb1(Image) values(@Image)";//注意这里要加@Image
comm.Parameters.Add("@Image", System.Data.SqlDbType.Image,data.Length);
comm.Parameters[].Value = data;
comm.ExecuteNonQuery();
conn.Close();
}

从数据库中读取:

        private void getImageFromSqlServer()
{
SqlDataAdapter sda = new SqlDataAdapter("select * from tb1", connectString);
DataTable dt = new DataTable();
sda.Fill(dt);
byte[] data = (byte[])dt.Rows[][];
MemoryStream ms = new MemoryStream();
ms.Write(data, , data.Length);
ms.Seek(, SeekOrigin.Begin);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();
iv2.Source = bi;
}

原作者:https://blog.csdn.net/qq_30975833/article/details/52294603