本文实例为大家分享了c#实现上传下载图片的具体代码,供大家参考,具体内容如下
1.首先我们通过流来上传下载图片,所有操作只停留在流这一层
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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.通过将图片转化为流然后转化为字节;将字节转化为流,然后加载图片
图片转化为字节的代码:
1
2
3
4
5
6
7
8
9
10
11
|
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;
}
|
字节转化为图片的代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
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;
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/ClearLoveQ/article/details/81112994