C#實(shí)現(xiàn)上傳下載圖片
本文實(shí)例為大家分享了C#實(shí)現(xiàn)上傳下載圖片的具體代碼,供大家參考,具體內(nèi)容如下
1.首先我們通過(guò)流來(lái)上傳下載圖片,所有操作只停留在流這一層
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();
}

分別點(diǎn)擊左側(cè)和右側(cè)按鈕,則將左側(cè)圖片加載到右側(cè):(PictureBox的SizeMode屬性可以設(shè)置圖片的填充方式)

2.通過(guò)將圖片轉(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); //及時(shí)定位流的開(kāi)始位置
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;
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- C#實(shí)現(xiàn)把圖片下載到服務(wù)器代碼
- Asp.net(C#)讀取數(shù)據(jù)庫(kù)并生成JS文件制作首頁(yè)圖片切換效果(附demo源碼下載)
- C#.NET中如何批量插入大量數(shù)據(jù)到數(shù)據(jù)庫(kù)中
- c#批量上傳圖片到服務(wù)器示例分享
- C#實(shí)現(xiàn)SQL批量插入數(shù)據(jù)到表的方法
- C#/.Net 中快速批量給SQLite數(shù)據(jù)庫(kù)插入測(cè)試數(shù)據(jù)
- C#實(shí)現(xiàn)的文件批量重命名功能示例
- C#實(shí)現(xiàn)批量下載圖片到本地示例代碼
相關(guān)文章
C#通過(guò)PInvoke調(diào)用c++函數(shù)的備忘錄的實(shí)例詳解
這篇文章主要介紹了C#通過(guò)PInvoke調(diào)用c++函數(shù)的備忘錄的實(shí)例以及相關(guān)知識(shí)點(diǎn)內(nèi)容,有興趣的朋友們學(xué)習(xí)下。2019-08-08
c#使用Socket發(fā)送HTTP/HTTPS請(qǐng)求的實(shí)現(xiàn)代碼
這篇文章主要介紹了c#使用Socket發(fā)送HTTP/HTTPS請(qǐng)求的實(shí)現(xiàn)代碼,需要的朋友可以參考下2017-09-09
C#實(shí)現(xiàn)Zip壓縮目錄中所有文件的方法
這篇文章主要介紹了C#實(shí)現(xiàn)Zip壓縮目錄中所有文件的方法,涉及C#針對(duì)文件的讀寫(xiě)與zip壓縮相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07

