using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
#region 图片与二进制流互转
//将图片转换成二进制流
byte[] bytes = GetPictureData(@"C:\Users\test\Documents\Visual Studio 2015\Projects\test\ConsoleApplication1\ConsoleApplication1\Img\Hydrangeas.jpg");
//将二进制流转换成图片保存
using (MemoryStream mem = new MemoryStream())
{
Image img = ReturnPhoto(bytes);
//这句很重要,不然不能正确保存图片或出错(关键就这一句)
Bitmap bmp = new Bitmap(img);
//保存到磁盘文件
bmp.Save(@"C:\Users\test\Documents\Visual Studio 2015\Projects\test\ConsoleApplication1\ConsoleApplication1\Img\Hydrangeas111.jpg", img.RawFormat);
bmp.Dispose();
}
#endregion
#region 读取文件转成二进制流, 然后保二进制流转成图片
using (FileStream fsread = new FileStream(@"C:\Users\test\Documents\Visual Studio 2015\Projects\test\ConsoleApplication1\ConsoleApplication1\Img\Hydrangeas.jpg", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (FileStream fs = new FileStream(@"C:\Users\test\Documents\Visual Studio 2015\Projects\test\ConsoleApplication1\ConsoleApplication1\Img\Hydrangeas222.jpg", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
byte[] buffer = new byte[1024 * 1024];
int bufferLength = 0;
int bufferCount = 1;
while ((bufferLength = fsread.Read(buffer, 0, buffer.Length)) > 0)
{
fs.Write(buffer, 0, buffer.Length);
Console.WriteLine("当前读取第{0}次", bufferCount++);
}
}
}
#endregion
Console.ReadKey();
}
public static byte[] GetPictureData(string imagepath)
{
FileStream fs = new FileStream(imagepath, FileMode.Open);//可以是其他重载方法
byte[] bytes= new byte[fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
return bytes;
}
public static Image ReturnPhoto(byte[] streamByte)
{
MemoryStream ms = new MemoryStream(streamByte);
Image img = Image.FromStream(ms);
return img;
}
}
}
C#学习图片与二进制流互转
猜你喜欢
转载自blog.csdn.net/qq_24432127/article/details/85616693
今日推荐
周排行