亲宝软件园·资讯

展开

C#实现上传下载图片 C#实现上传下载图片

ClearLoveQ 人气:0

1.首先我们通过流来上传下载图片,所有操作只停留在流这一层

MemoryStream ms;
  //左侧按钮
  private void button1_Click(object sender, EventArgs e)
  {  
   ms = new MemoryStream();
   Image bi =pictureBox1.Image;
   bi.Save(ms, pictureBox1.Image.RawFormat);//将图片存入流中 
  }
  //右侧按钮
  private void button2_Click(object sender, EventArgs e)
  {
   Image img = Image.FromStream(ms, true);
   pictureBox2.Image = img; 
   ms.Close();  
  }

分别点击左侧和右侧按钮,则将左侧图片加载到右侧:(PictureBox的SizeMode属性可以设置图片的填充方式)

2.通过将图片转化为流然后转化为字节;将字节转化为流,然后加载图片

图片转化为字节的代码:

public static byte[] ImgToByte(Image img, System.Drawing.Imaging.ImageFormat imgFormat)
  {
   Bitmap bmp = new Bitmap(img);
   MemoryStream memStream = new MemoryStream();
   bmp.Save(memStream, imgFormat);
   memStream.Seek(0, SeekOrigin.Begin); //及时定位流的开始位置
   byte[] btImage = new byte[memStream.Length];
   memStream.Read(btImage, 0, btImage.Length);
   memStream.Close();
   return btImage;
 }

字节转化为图片的代码:

public static Image ByteToImg(byte[] btImage)
  {
   MemoryStream memStream = new MemoryStream();
   //Stream memStream = null;
   memStream.Write(btImage, 0, btImage.Length);
   memStream.Position = 0;
   memStream.Seek(0, SeekOrigin.Begin);
   //Bitmap bmp = new Bitmap(memStream, true);
   Image img;
   try
   {
    img = Image.FromStream(memStream, true);
    memStream.Close();
    //img = new Bitmap(memStream);
   }
   catch (Exception ex)
   {
    img = null;
    MessageBox.Show(ex + "");
   }
   finally
   {
    memStream.Close();
   }
   return img;
}

加载全部内容

相关教程
猜你喜欢
用户评论