using (FileStream fs = System.IO.File.Create(imgSrc))
{
using (Stream stream=CompressImage(imgFile.OpenReadStream()))
{
byte[] srcBuf = StreamToBytes(stream);
fs.Write(srcBuf, 0, srcBuf.Length);
fs.Flush();
}
}
//Stream转Byte
public byte[] StreamToBytes(Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
// 设置当前流的位置为流的开始
stream.Seek(0, SeekOrigin.Begin);
return bytes;
};
//处理图片
private Stream CompressImage(Stream stream)
{
//Image image = Image.FromStream(stream);
using (Image image = Image.FromStream(stream))
{
Size size = new Size(200, 200);
int sourceWidth = image.Width;
//获取图片高度
int sourceHeight = image.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
//计算宽度的缩放比例
nPercentW = ((float)size.Width / (float)sourceWidth);
//计算高度的缩放比例
nPercentH = ((float)size.Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
//期望的宽度
int destWidth = (int)(sourceWidth * nPercent);
//期望的高度
int destHeight = (int)(sourceHeight * nPercent);
using (Bitmap bitmap = new Bitmap(destWidth, destHeight))
{
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
//绘制图像
graphics.DrawImage(image, 0, 0, destWidth, destHeight);
Stream memoryStream = new MemoryStream();
image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
graphics.Dispose();
return memoryStream;
}
}
}
}
为什么当我不对Stream调用CompressImage方法可以输出到文件,但是调用之后输出的文件就提示格式不正确
CompressImage方法返回前,试试重置一下 memoryStream 的Position到头部.
或者StreamToBytes 方法里面读流之前重置一下也可以,就是重复你读流之后的那句代码