C#實現(xiàn)上傳下載圖片
本文實例為大家分享了C#實現(xiàn)上傳下載圖片的具體代碼,供大家參考,具體內(nèi)容如下
1.首先我們通過流來上傳下載圖片,所有操作只停留在流這一層
MemoryStream ms; //左側(cè)按鈕 private void button1_Click(object sender, EventArgs e) { ms = new MemoryStream(); Image bi =pictureBox1.Image; bi.Save(ms, pictureBox1.Image.RawFormat);//將圖片存入流中 } //右側(cè)按鈕 private void button2_Click(object sender, EventArgs e) { Image img = Image.FromStream(ms, true); pictureBox2.Image = img; ms.Close(); }
分別點擊左側(cè)和右側(cè)按鈕,則將左側(cè)圖片加載到右側(cè):(PictureBox的SizeMode屬性可以設(shè)置圖片的填充方式)
2.通過將圖片轉(zhuǎn)化為流然后轉(zhuǎn)化為字節(jié);將字節(jié)轉(zhuǎn)化為流,然后加載圖片
圖片轉(zhuǎn)化為字節(jié)的代碼:
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; }
字節(jié)轉(zhuǎn)化為圖片的代碼:
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; }
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#通過PInvoke調(diào)用c++函數(shù)的備忘錄的實例詳解
這篇文章主要介紹了C#通過PInvoke調(diào)用c++函數(shù)的備忘錄的實例以及相關(guān)知識點內(nèi)容,有興趣的朋友們學習下。2019-08-08c#使用Socket發(fā)送HTTP/HTTPS請求的實現(xiàn)代碼
這篇文章主要介紹了c#使用Socket發(fā)送HTTP/HTTPS請求的實現(xiàn)代碼,需要的朋友可以參考下2017-09-09